Home > Net >  If statement inside Do while loop not working
If statement inside Do while loop not working

Time:12-28

I am new at excel VBA and i am facing this problem, i am writing a code which supposed to see the value of a cell and then goes through a list of numbers and gets the next higher or equal number through this list.

The problem is that the code works fine and gets me the next higher number, but when it comes to the equal part it doesn't work, i wrote an if statement which breaks the loops when the condition of (equal) is achieved but it seems that this line is not executed. Would please help me figure why is this happening

my code looks something like this

Do While ([c12] < [h13])
If ([c12] = [h13]) Then
    Exit Do
End If
[c12].Value = Worksheets("lists").Cells(cb, 9)
cb = cb   1
Loop

CodePudding user response:

When your If statement would be True your While will always be False so the loop ends before that If ever triggers.

If you were to change the While to a Do you can see the If statement executing.

    Do
        If ([c12] = [h13]) Then
            Exit Do
        End If
        [c12].Value = Worksheets("lists").Cells(cb, 9)
        cb = cb   1
    Loop

CodePudding user response:

I think I agree with @Warcupine that the "If" is unnecessary.

How about building your "If" condition just into the conditional loop itself?

Do
   [c12].Value = Worksheets("lists").Cells(cb, 9)
   cb = cb   1
Loop Until ([c12] >= [h13])
  • Related