Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Exit a while loop in VBA/VBS

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
like image 429
bigbryan Avatar asked Sep 26 '15 12:09

bigbryan


People also ask

How do you exit a while loop in VBScript?

Using Do While or Do Until allows you to stop execution of the loop using Exit Do instead of using trickery with your loop condition to maintain the While ... Wend syntax. I would recommend using that instead.

How do you exit a while loop in VBA?

Exit Do Loop We can exit any Do loop by using the Exit Do statement.

How do you exit a VBScript code?

VBA/VBScript Differences VBA supports the End statement, which immediately terminates execution of code and, in the case of Visual Basic, terminates the application.

How do you break a loop in Visual Basic?

In visual basic, we can exit or terminate the execution of the while loop immediately by using Exit keyword. Following is the example of using Exit keyword in a while loop to terminate loop execution in a visual basic programming language.


1 Answers

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
like image 131
omegastripes Avatar answered Sep 27 '22 20:09

omegastripes