You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Excel VBA实现跨工作表逐行递增索引(依次取各表一行)

跨工作表逐行交替递增索引编号需求及问题

我有4个工作表,另有一个工作簿包含数据表。需要为从这4个工作表中提取的每一行递增索引编号,要求逐行递增、依次从每个工作表取一行并连续编号(效果为:先给Sheet1第1行编1,Sheet2第1行编2,Sheet3第1行编3,Sheet4第1行编4;接着Sheet1第2行编5,Sheet2第2行编6,以此类推)。

以下是我目前的代码,但它仅能在单个工作表内实现行索引递增:

Sub IncrementIndexesAcrossSheets()
    Dim ws As Worksheet
    Dim dataRange As Range
    Dim rowIndex As Long
    Dim lastRowIndex As Long
    
    ' Initialize rowIndex to 1
    rowIndex = 1
    
    ' Loop through all sheets in the workbook
    For Each ws In ThisWorkbook.Sheets
        ' Skip sheets without data
        If WorksheetFunction.CountA(ws.Cells) > 0 Then
            ' Set the dataRange to the appropriate column (Column B in this case)
            Set dataRange = ws.Range("B2:B" & ws.Cells(Rows.Count, 2).End(xlUp).Row)
            
            ' Loop through each cell in the dataRange
            For Each cell In dataRange
                ' Set the value of the Index column (Column A) to the current rowIndex
                cell.Offset(0, -1).Value = rowIndex
                ' Increment the rowIndex
                rowIndex = rowIndex + 1
            Next cell
            
            ' Update lastRowIndex with the last used index on the current sheet
            lastRowIndex = rowIndex - 1
        End If
    Next ws
End Sub

示例数据与预期输出

示例数据

每个工作表的B列从第2行开始存在数据,各表数据行数如下:

  • Sheet1:3行数据(B2-B4)
  • Sheet2:2行数据(B2-B3)
  • Sheet3:3行数据(B2-B4)
  • Sheet4:2行数据(B2-B3)

预期输出

  • Sheet1:A2=1,A3=5,A4=9
  • Sheet2:A2=2,A3=6
  • Sheet3:A2=3,A3=7,A4=10
  • Sheet4:A2=4,A3=8

我是VBA新手,曾搜索多种解决方案,但均只能实现单表内递增或跨表单个单元格递增,恳请帮助我编写符合需求的代码,我非常想学习这类逻辑的实现方式。此前的问题已被关闭,故重新发布更清晰的问询。

内容的提问来源于stack exchange,提问作者Carrot

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.10 19:01:22