Excel VBA For Loop过早终止

时间:2018-04-17 22:42:48

标签: vba excel-vba excel

Sub AssignNum()
    Dim iTotalCol As Integer
    Dim iNBRFirstRow As Integer
    Dim iLastRow As Integer
    Dim iHRISCol As Integer
    Dim strColLetter As String
    Dim iCount As Integer
    Dim iNum As Integer

    iNum = 1

    With shtReport
        iHRISCol = .Range("rngHRISID").Column
        iTotalCol = .Range("rngStart").Column
        iNBRFirstRow = .Range("rngHRISID").Row + 1
        iLastRow = .Cells(.Rows.Count, iHRISCol).End(xlUp).Row
        .Range("A" & iNBRFirstRow & ":A" & iLastRow).ClearContents

        'Assign Num number if total > 0 and Parent HRIS ID equals HRIS ID
        For iCount = iNBRFirstRow To iLastRow
            If .Cells(iCount, iTotalCol).Value > 0 And _
            .Cells(iCount, iHRISCol) = .Cells(iCount, iHRISCol - 1) Then
                 .Range("A" & iCount).Value = iNum
                 iNum = iNum + 1
            End If
        Next iCount
    End With
End Sub

此处,iLastRow的值为761,iNBRFirstRow为7.因此,iCount应循环7到761,但它会在184处停止,过早终止for循环。我无法弄清楚造成这个问题的原因。有人可以帮忙吗?

1 个答案:

答案 0 :(得分:1)

更新了检查错误的代码,并将所有Ints更改为Longs

Option Explicit

Public Sub AssignNum()
    Dim iTotalCol As Long
    Dim iNBRFirstRow As Long
    Dim iLastRow As Long
    Dim iHRISCol As Long
    Dim strColLetter As String
    Dim iCount As Long
    Dim iNum As Long

    iNum = 1

    With shtReport
        iHRISCol = .Range("rngHRISID").Column
        iTotalCol = .Range("rngStart").Column
        iNBRFirstRow = .Range("rngHRISID").Row + 1
        iLastRow = .Cells(.Rows.Count, iHRISCol).End(xlUp).Row
        .Range("A" & iNBRFirstRow & ":A" & iLastRow).ClearContents

        'Assign Num number if total > 0 and Parent HRIS ID equals HRIS ID
        For iCount = iNBRFirstRow To iLastRow
            If Not IsError(.Cells(iCount, iTotalCol)) And _
               Not IsError(.Cells(iCount, iHRISCol)) And _
               Not IsError(.Cells(iCount, iHRISCol - 1)) Then
                    If .Cells(iCount, iTotalCol).Value > 0 And _
                       .Cells(iCount, iHRISCol) = .Cells(iCount, iHRISCol - 1) Then
                            .Range("A" & iCount).Value = iNum
                            iNum = iNum + 1
                    End If
            End If
        Next iCount
    End With
End Sub