The for-command doesn't allow any extra condition, it runs a loop for a specific number of iterations.
Put the condition in an extra If
-statement:
For i = 2 To 20
If Cells(i, 23).Value = "x" Then
...
End If
Next i
Hint: Tell VBA always on which worksheet you want to work. With your code, you will work on the active sheet and that is not always the sheet you want. For more details, take the time and read How to avoid using Select in Excel VBA
For those who are curious what will happen when writing
i = 2
For i = 2 To 20 And Cells(i, 23).Value = "x"
(...)
Next
VBA will evaluate the term 20 And Cells(i, 23).Value = "x"
and convert it into a number. It will first check the value of Cells(2, 23)
: If this is "x"
, the term Cells(i, 23).Value = "x"
will be True
, which is represented as -1, which is a bit pattern where all bits are set to 1. Now VBA will evaluate 20 And -1
(using arithmetic And) and this results in 20.
This term is evaluated only once, before the loop starts, and therefore the loop will run from 2 to 20.
If, however, the value in Cells(i, 23)
is something different, the term Cells(i, 23).Value = "x"
will be False
, which is represented as 0 (all bits are 0). 20 And 0
will be 0 and therefore the loop will not run at all.