对于Excel VBA中的嵌套循环

时间:2018-07-02 19:50:43

标签: vba excel-vba nested-loops excel

我有一个For循环来查看列,并且需要跳过两列。当我运行此代码时,第二个For循环(使用iCol)不起作用。

当我在循环外进行测试时,循环内的代码可以正常工作。我尝试了不同的选项以将两列从For循环中排除(选择大小写),但没有任何效果。

Dim rng As Range
Dim n As Long
Dim iRow As Long
Dim iCol As Long
Dim NameColNum As Integer
Dim LNameColNum As Integer
Dim DoBColNum As Integer
Dim SColNum As Integer
Dim JColNum As Integer

' Sets data range
Set rng = Range(Range("A1"), Range("A" & Rows.Count).End(xlUp))

NameColNum = Application.Match("First Name", rng.EntireRow(1), 0)
LNameColNum = Application.Match("Last Name", rng.EntireRow(1), 0)
DoBColNum = Application.Match("Birth Date", rng.EntireRow(1), 0)

' For S and J cases
SColNum = Application.Match("Created User ID", rng.EntireRow(1), 0)
JColNum = Application.Match("W Name", rng.EntireRow(1), 0)

For iRow = 2 To rng.Rows.Count

If rng.Cells(iRow, NameColNum) = rng.Cells(iRow + 1, NameColNum) And _
   rng.Cells(iRow, LNameColNum) = rng.Cells(iRow + 1, LNameColNum) And _
   rng.Cells(iRow, DoBColNum) = rng.Cells(iRow + 1, DoBColNum) Then

        If rng.Cells(iRow, SColNum).Value = "STAGE" Then
            rng.EntireRow(iRow).Interior.ColorIndex = 3
            rng.EntireRow(iRow + 1).Interior.ColorIndex = 3
        End If

        If rng.Cells(iRow, JColNum) = "Smith" Then
                rng.EntireRow(iRow).Interior.ColorIndex = 4
                rng.EntireRow(iRow + 1).Interior.ColorIndex = 4
        End If

        For iCol = DoBColNum + 1 To rng.Columns.Count
            If iCol <> SColNum And iCol <> JColNum Then
                If rng.Cells(iRow, iCol).Value <> rng.Cells(iRow + 1, iCol).Value And _
                    rng.EntireRow(iRow).Interior.ColorIndex = -4142 Then
                    rng.EntireRow(iRow).Interior.ColorIndex = iCol
                    rng.EntireRow(iRow + 1).Interior.ColorIndex = iCol
                End If
            End If
        Next 'iCol
End If
Next 'iRow

1 个答案:

答案 0 :(得分:3)

rng.Columns.Count始终等于1,因为您将rng行中的Set限制为A列。因此,您的第二个循环将永远不会运行(您正在尝试循环4 to 1等)。

相反,更改Set rng = Range(Range("A1"), Range("A" & Rows.Count).End(xlUp))以包括您使用的所有列,并从另一行的A列获取最后一行的值。

建议的解决方法:

Dim lastrow As Long
lastrow = Cells(Rows.Count, "A").End(xlUp).Row
' Sets data range
Set rng = Range(Range("A1"), Range("S" & lastrow))