在vba msgbox中不使用goto循环的方法
我试图find一种方法来避免在VBA中使用GoTo循环,因为我知道它们会导致严重的混淆和问题。 我有一个用户InputBox
,其中用户定义了一个variables,当前if语句中有3个选项,if = Y ElseIf = N,否则GoTo Start。
然而,这对于用户错误inputvariables即Y#等的情况非常有效,但是当前用户想要closuresinput框,即点击取消或交叉时,我遇到了问题。
所以我想知道是否有一个更聪明的解决scheme,或者我坚持这个hicup?
我的代码如下,这只是一个testing集,用于testing我添加到我的主代码中的这个新function。
Sub MsgBox_Test () Dim TestVariable As String VariableEntrey: TestVariable = InputBox(" Y or N") If TestVariable = "Y" Or TestVariable = "y" Then MsgBox ("Yeyy") ElseIf TestVariable = "N" Or TestVariable = "n" Then MsgBox ("Awww") Else: GoTo VariableEntrey End If End Sub
感谢您能够提供的任何帮助
Option Explicit Sub MsgBox_Test() Dim TestVariable As String Dim done As Boolean Do TestVariable = InputBox(" Y or N") done = True ' preload exit value If LCase(TestVariable) = "y" Then MsgBox ("Yeyy") ElseIf LCase(TestVariable) = "n" Then MsgBox ("Awww") ElseIf Len(TestVariable) > 0 Then done = False ' abort exit End If Loop Until done End Sub
你可以尝试一个Do... Loop Until
构造,直到你得到一个可以接受的答案。 例如:
Sub GetAnswer() Dim strAnswer As String Do strAnswer = InputBox("Y or N") Loop Until strAnswer Like "[YyNn]" MsgBox "Thanks for your answer of: " & strAnswer End Sub
请参阅Like
运算符上的文档以防止单独检查y
, Y
, n
和N
我会使用一个MsgBox
而不是一个InputBox
。
Sub GetYesNo() Dim answer As VbMsgBoxResult answer = MsgBox("Yes or No?", vbYesNo) If answer = vbYes Then 'do something Else 'do something else End If End Sub
您可以使用Do
>> Loop Until
循环来删除GoTo
。
此外,您可以使用UCase(TestVariable)
从您的UCase(TestVariable)
中删除Or
。
Sub MsgBox_Test() Dim TestVariable As String Do TestVariable = InputBox(" Y or N") If UCase(TestVariable) = "Y" Then MsgBox ("Yeyy") ElseIf UCase(TestVariable) = "N" Then MsgBox ("Awww") End If Loop Until UCase(TestVariable) Like "[YN]" End Sub
你可以试试Do .... Loop
here:
编辑:加上单个字符或空input的限制
Dim TestVariable As String TestVariable = InputBox(" Y or N") Do While (TestVariable = "N" Or TestVariable = "n" or Len(TestVariable) > 1) MsgBox ("Awww") TestVariable = InputBox(" Y or N") Loop If TestVariable = "Y" Or TestVariable = "y" Then MsgBox ("Yeyy") End if