7

I have an Excel VBA program that loops through each row of data in a data sheet.

My goal is to exit the while loop once boolean bFound is set as True.

I think my condition "Or bFound=True" might be incorrect.

bFound = False
While Sheets("Data").Cells(iRow, 1) <> "" Or bFound = True

    If Sheets("Data").Cells(iRow, 11) = Sheets("Data2").Cells(iRow, 1) Then
        bFound = True
    End If

    iRow = iRow + 1
Wend
'exit loop after the boolean=true
2
  • 1
    Replace the Or with an And Commented Sep 26, 2015 at 13:03
  • possible duplicate of Exit a while loop in VBS/VBA Commented Sep 26, 2015 at 21:41

2 Answers 2

15

Use Do ... Loop and Exit Do

bFound = False
Do While Sheets("Data").Cells(iRow, 1) <> ""
    bFound = Sheets("Data").Cells(iRow, 11) = Sheets("Data2").Cells(iRow, 1)
    If bFound Then Exit Do
    iRow = iRow + 1
Loop
Sign up to request clarification or add additional context in comments.

1 Comment

@bigbryan, note that outside the loop iRow points to the row where exit condition has been matched, but not to the next row as it intended in your code.
6

Flip the logic around, I expect this will work for you:

bFound = False
While Sheets("Data").Cells(iRow, 1) <> "" And bFound = False

    If Sheets("Data").Cells(iRow, 11) = Sheets("Data2").Cells(iRow, 1) Then
        bFound = True
    End If

    iRow = iRow + 1
Wend

Explanation:

While Sheets("Data").Cells(iRow, 1) <> "" And bFound = False

will allow the loop to carry on only while we still have data to process AND we still haven't changed bFound, which has initial value of False.


Another option is to use the breakable form of While in VBS:

Do While Sheets("Data").Cells(iRow, 1) <> ""

    If Sheets("Data").Cells(iRow, 11) = Sheets("Data2").Cells(iRow, 1) Then Exit Do

    iRow = iRow + 1

Loop

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.