Reputation: 35
I have a For loop to look at columns and need to skip two columns. When I run this code, the second For loop (with iCol) does not work.
The code within the loop works fine when I tested outside of the loop. I have tried different options to exclude the two columns from the For loop (select case) but nothing works.
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
Upvotes: 0
Views: 1081
Reputation: 5450
rng.Columns.Count
is always going to equal 1, because you limited rng
to column A on your Set
line. Because of this, your second loop will never run (You're trying to loop 4 to 1
, etc.).
Instead, change Set rng = Range(Range("A1"), Range("A" & Rows.Count).End(xlUp))
to include all columns that your working with, and get the last row value from column A on another line.
Suggested fix:
Dim lastrow As Long
lastrow = Cells(Rows.Count, "A").End(xlUp).Row
' Sets data range
Set rng = Range(Range("A1"), Range("S" & lastrow))
Upvotes: 3