我读过数据语句的利弊ON X GOTO
,并且非常清楚 Calls 和 Jmp 替代方案以及它被认为是不好的做法,但我希望有一个简单的替代解决方案。同样(不仅仅是懒惰),但为每个替代方案使用大量代码行似乎效率低下且不太容易阅读。
本质上我想要一个简单的替代方案(用英文代码而不是任何特定代码编写,但在 VBA 中需要):
Input x
On x Goto LineA, LineB, LineC
LineA....
End
LineB....
End
LineC....
End
或者:
List of alternatives (choice = 1, choice = 2, choice = 3)
Input choice
on choice someVariable = string1, string2, string3
(Remaining code which uses that string)
两者非常相似,请记住列表可以是任意长度并且字符串可以更长,但是由单个语句选择而不是在每种特定情况下跳转到新的代码行。
答案1
不要忽视最佳实践和建议。此代码完全可读,并且可满足您的需要而不会违反规则...
Sub test()
Select Case InputBox("Enter a value")
Case "1"
'Do things that are specific to "1"
Beep
'Or better still, call a specific sub
DoSomething1
Case "2"
'Do things that are specific to "2"
Beep
'Or better still, call a specific sub
DoSomething2
Case "3"
'Do things that are specific to "3"
Beep
'Or better still, call a specific sub
DoSomething3
Case Else
'Do Nothing
End Select
End Sub
Sub DoSomething1()
Beep
End Sub
Sub DoSomething2()
Beep
Beep
End Sub
Sub DoSomething3()
Beep
Beep
Beep
End Sub