VBA" Loop"在If Else声明中

时间:2015-03-28 16:36:29

标签: vba loops excel-vba excel

任何人都可以告诉我为什么我会收到编译错误:"循环没有做"对于以下代码。

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

3 个答案:

答案 0 :(得分:1)

格式化代码后,错误很明显。您的Loop位于End If之前。只需在End If之后移动它。

答案 1 :(得分:1)

阅读你的代码,似乎你只想在答案是" No"时才循环。 您使用的语法不正确,您需要在Exit Do块中嵌套If破坏子句,但不能在其中嵌套Loop关键字。这是应该如何:

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

或者,您可以使用If的{​​{1}}关键字来避免While阻止:

Do Loop

答案 2 :(得分:0)

更改为:

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

If ans = vbYes Then Exit Do
Loop

我认为这就是你要做的事情,但你的语法略有不同。

我会添加更多解释,但我在手机上。

这里有关于循环语法的更多信息http://www.excel-easy.com/vba/loop.html

相关问题