首页 > 解决方案 > 对于 Excel VBA 中的嵌套循环

问题描述

我有一个 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

标签: vbaexcelnested-loops

解决方案


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))

推荐阅读