Exit while loop in VBA / VBS

I have an Excel VBA program that goes through every row of data in a data sheet.

My goal is to exit the while loop when the boolean is bFoundset as True.

I think my condition β€œOr bFound = True” might be wrong.

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
+4
source share
2 answers

Use Do ... LoopandExit 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
+6
source

Turn the logic around, I expect this to 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

allows only when we still have data to process. And we still have not changed bFound, which has an initial meaning False.


- While 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
+5

Source: https://habr.com/ru/post/1609094/


All Articles