📅  最后修改于: 2023-12-03 14:52:17.119000             🧑  作者: Mango
在 Excel VBA 中,没有 switch 语句,但可以通过一些方法模拟 switch 语句的功能。
Select Case 语句与 switch 语句相比较相似,可以用来模拟 switch 语句的功能。
Sub demo()
Dim num As Integer
num = 1
Select Case num
Case 1
MsgBox "num = 1"
Case 2
MsgBox "num = 2"
Case Else
MsgBox "num 不为 1 或 2"
End Select
End Sub
此方法使用 if 语句和逻辑运算符(And 和 Or)加强代码的逻辑性,以实现 switch 语句的功能。
Sub demo()
Dim fruit As String
fruit = "apple"
If fruit = "apple" Or fruit = "cherry" Then
MsgBox "fruit is apple or cherry"
ElseIf fruit = "banana" Then
MsgBox "fruit is banana"
Else
MsgBox "fruit is other"
End If
End Sub
此方法使用数组作为 case 值,配合 for 循环来模拟 switch 语句的功能。缺点是代码复杂,可读性差。
Sub demo()
Dim fruit As String
Dim fruits(2) As String
fruits(0) = "apple"
fruits(1) = "banana"
fruits(2) = "cherry"
fruit = "apple"
For i = 0 To UBound(fruits)
If fruit = fruits(i) Then
Select Case i
Case 0
MsgBox "fruit is apple"
Case 1
MsgBox "fruit is banana"
Case 2
MsgBox "fruit is cherry"
End Select
Exit For
End If
Next i
End Sub
通过以上三种方法,我们可以在 Excel VBA 中实现类似 switch 语句的功能,提高代码的可读性和逻辑性。