运行macros并在语句条件满足时结束
我有一个IF Else语句,用于检查工作簿中是否存在电子表格。 如果它确实存在,则意味着运行特定的macros,然后停止。 如果电子表格不存在,它应该运行到IF语句的末尾,然后生成带有错误消息的MSGBOX。
一旦条件满足,我不能让IF语句结束,macros已经运行。
代码是:
Dim k As Integer Dim t As String Dim x As Integer k = Sheets.Count x = 1 While x <= k t = Sheets(x).Name If t = "Details" Then Call Details_1 Else x = x + 1 End If Wend If x > k Then MsgBox "Something seems to have gone wrong." & vbCrLf & "Please ensure that you have pressed 'Button 1' before you press any of the other buttons", vbOKOnly, "ERROR MESSAGE" End If
我假设你的意思是调用Details_1,然后继续While循环,这是你不想要的。 如果是的话,我会build议你改变你的代码是这样的:
Dim k As Integer Dim t As String Dim x As Integer k = Sheets.Count x = 1 Do While x <= k t = Sheets(x).Name If t = "Details" Then Call Details_1 Exit Do Else x = x + 1 End If Loop If x > k Then MsgBox "Something seems to have gone wrong." & vbCrLf & "Please ensure that you have pressed 'Button 1' before you press any of the other buttons", vbOKOnly, "ERROR MESSAGE" End If
此代码应循环显示表单,直到find详细信息,调用Details_1,然后继续下一部分代码
移动x = x + 1
,使它在第一个End If
。 在调用macros之后, x = x + 1
不会被执行,而x则始终是<= k。