Borwick
Borwick

Reputation: 3

VBA <> function is not working as expected

I am comparing two cells that contain numbers either 1, 2, 3, or 4. Inside a loop, I compare these integers from both cells. If they do not match (<>) then perform an Exit for next. VBA ignores my code and continues through the loop. Using debug I see this. This is basic logic laws. Any thoughts?

hdv = a number 1 to 4 adv = a number 1 to 4 row is a loop 1 to 100

      For loop= 1 To 100
                hdv = Worksheets("20002018").Cells(row, 1).Value
                    adv = Worksheets("20002018").Cells(row, 2).Value
                        If hdv <> adv Then Exit For

' if false perform some stuff here. Next loop

Worksheets("20002018").Cells(row, 1) contains 1 Worksheets("20002018").Cells(row, 2) contains 2 comparing these two values should be enough to exit the loop

Upvotes: 0

Views: 151

Answers (1)

user11655492
user11655492

Reputation: 151

Your code will not compile when loop is used as the increment in the For ... Next. Loop is a reserved word in VBA and has another purpose.

Whatever you change it to, the same should probably be used instead of row in,

hdv = Worksheets("20002018").Cells(row, 1).Value
adv = Worksheets("20002018").Cells(row, 2).Value

Changing row to whatever numerical variable you use to increment the loop will increase the referenced row on the worksheet for each iteration of the For ... Next loop until it exits.

dim LOOPS as long, hdv as long, adv as long

for LOOPS =1 to 100
  hdv = Worksheets("20002018").Cells(LOOPS, 1).Value
  adv = Worksheets("20002018").Cells(LOOPS, 2).Value
  If hdv <> adv Then Exit For

   'other stuff

Next LOOPS

Upvotes: 1

Related Questions