用于从选定行自动填充序列号的Excel VBA代码

用于从选定行自动填充序列号的Excel VBA代码,excel,vba,Excel,Vba,我尝试使用以下代码从数据输入表单中自动填充序列号。我的问题是,它计算最后一行,序列号从这个数字开始。当我把数据输入第五行时,它从4开始计数。但是因为它是我计数的第一行,所以它应该是1。如何解决这个问题 Set shSegment = ThisWorkbook.Sheets(sSegmentName) iCurrentRow = shSegment.Range("A" & Application.Rows.Count).End(xlUp).Row + 1 With

我尝试使用以下代码从数据输入表单中自动填充序列号。我的问题是,它计算最后一行,序列号从这个数字开始。当我把数据输入第五行时,它从4开始计数。但是因为它是我计数的第一行,所以它应该是1。如何解决这个问题

Set shSegment = ThisWorkbook.Sheets(sSegmentName)

iCurrentRow = shSegment.Range("A" & Application.Rows.Count).End(xlUp).Row + 1

With shSegment

    
.Cells(iCurrentRow, 1) = iCurrentRow - 1

请试试这个。评论中有解释

Set shSegment = ThisWorkbook.Sheets(sSegmentName)

iCurrentRow = shSegment.Range("A" & Application.Rows.Count).End(xlUp).Row + 1

With shSegment
    'Test if previous row is a number
    If IsNumeric(.Cells(iCurrentRow - 1, 1)) Then
        ' If yes, add 1 to its previous row's value
        .Cells(iCurrentRow, 1) = .Cells(iCurrentRow - 1, 1) + 1
    Else
        ' If no, reset to 1 (previous row was the header)
        .Cells(iCurrentRow, 1) = 1
    End If