简体   繁体   中英

VBA “Loop” within If Else statement

Can anyone tell me why I would be getting a compile error: "Loop without do" for the following code.

Sub Burrito_log()

    Dim j As Long
    j = 1
    Do
        x = InputBox("How many burritos did you have today?")
        Cells(j, 2) = x
        Cells(j, 1) = Date
        j = j + 1

        ans = MsgBox("Burrito Log", vbYesNo, "Are you done inputting?")
        If ans = vbYes Then
            'Do nothing
        Else
            Loop
        End If

End Sub

After formating your code the error is obvious. Your Loop is located before your End If . Just move it after End If .

Reading your code, it seems you want to loop only if the answer is "No". The syntax you use is incorrect, you need to nest an Exit Do breaking clause in the If block but you cannot nest the Loop keyword inside. Here's how it should be:

Sub Burrito_log()

    Dim j As Long
    j = 1
    Do
        x = InputBox("How many burritos did you have today?")
        Cells(j, 2) = x
        Cells(j, 1) = Date
        j = j + 1

        ans = MsgBox("Burrito Log", vbYesNo, "Are you done inputting?")
        If ans = vbYes Then
            Exit Do
        End If
    Loop
End Sub

Alternatively, you can avoid the If block by using the While keyword of the Do Loop :

Do While ans <> vbYes
    'no If block --> Exit Do needed
Loop

Change to:

ans = MsgBox("Burrito Log", vbYesNo, "Are you done inputting?") 

If ans = vbYes Then Exit Do
Loop

I think this is what you were trying to do, but you had the syntax off a bit.

I would add more explanation, but I'm on my phone.

There's more info on loop syntax here http://www.excel-easy.com/vba/loop.html

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM