VBA“;“循环”;在If-Else语句中
有人能告诉我为什么我会在下面的代码中出现编译错误:“Loop without do”VBA“;“循环”;在If-Else语句中,vba,loops,excel,Vba,Loops,Excel,有人能告诉我为什么我会在下面的代码中出现编译错误:“Loop without do” 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(
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
格式化代码后,错误很明显。您的
循环位于结束If
之前。如果
更改为:
ans = MsgBox("Burrito Log", vbYesNo, "Are you done inputting?")
If ans = vbYes Then Exit Do
Loop
我想这就是你想做的,但是你的语法有点错误
我想补充更多的解释,但我正在打电话
这里有更多关于循环语法的信息阅读您的代码,似乎您只想在答案为“否”时循环。 您使用的语法不正确,需要在
If
块中嵌套Exit Do
breaking子句,但不能在其中嵌套循环
关键字。以下是它应该是什么样子:
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
或者,您可以通过使用Do循环的While
关键字来避免If
块:
Do While ans <> vbYes
'no If block --> Exit Do needed
Loop
Do While ans vbYes
'如果需要块-->退出,则为否
环
Alexandre给了你答案。我还要强调的是,您的循环
没有中断
子句。请注意,如果你从未退出你的Do
,你将永远吃墨西哥煎饼。你必须先关闭if
块,然后才能关闭循环。