你真的会使用VBA的Select Case吗?
对于判断条件有多种分支的情况,使用Select Case替代If嵌套是个不错的选择,语法格式可以参考微软在线文档:[Select Case 语句](https://docs.microsoft.com/zh-cn/office/vba/language/reference/user-interface-help/select-case-statement?WT.mc_id=M365-MVP-334
对于判断条件有多种分支的情况,使用Select Case替代If嵌套是个不错的选择,语法格式可以参考微软在线文档:Select Case 语句。
似乎语法格式和用法都很简单,但是实际使用过程中可能就不是那回事了。下面示例来自于网友提问:下面的代码无论数组值如何变化,输出结果最多就到“运行5”,之后的分支永远无法执行。
Sub demo1()
Dim mxx(1 To 2), nxx(1 To 2)
nxx(1) = 0: nxx(2) = 10
mxx(1) = 0: mxx(2) = 100
Select Case mxx(1)
Case Is = nxx(1) And mxx(2) = nxx(2)
Debug.Print "运行1"
Case Is = nxx(1) And mxx(2) > nxx(2)
Debug.Print "运行2"
Case Is = nxx(1) And mxx(2) < nxx(2)
Debug.Print "运行3"
Case Is > nxx(1) And mxx(2) = nxx(2)
Debug.Print "运行4"
Case Is < nxx(1) And mxx(2) = nxx(2)
Debug.Print "运行5"
Case Is > nxx(1) And mxx(2) < nxx(2)
Debug.Print "运行6"
Case Is < nxx(1) And mxx(2) < nxx(2)
Debug.Print "运行7"
Case Is > nxx(1) And mxx(2) > nxx(2)
Debug.Print "运行8"
Case Is < nxx(1) And mxx(2) > nxx(2)
Debug.Print "运行9"
End Select
End Sub
其实网友之注意到有些Case分支没有执行,但是并没有注意到,即使被执行的分支,结果也不一定是对的。例如上述代码中
nxx(1) = 0: nxx(2) = 10
mxx(1) = 0: mxx(2) = 100
很明显 mxx(1) = nxx(1) And mxx(2) > nxx(2),应该是希望其使用如下的Case分支,但是运行结果却是运行1。
Case Is = nxx(1) And mxx(2) > nxx(2)
Debug.Print "运行2"
为什么会出现这个结果呢?这位网友没有理解Case语句的用法,第一个Case分支相当于If mxx(1) = (nxx(1) And mxx(2) = nxx(2)),此时将相关值代入其中,因此条件表达式变为mxx(1) = (0 And 10 > 100),进而简化为mxx(1) = 0,第一个分支条件满足,所以输出结果为运行1,然后执行End Select。由于类似的原因,后续几个分支不可能被执行。
从代码过程分析,可以看出这位网友希望实现的是根据两个数组元素的大小关系,进而执行不同的操作,那么应该使用如下代码。
Sub demo()
Dim mxx(1 To 2), nxx(1 To 2)
nxx(1) = 0: nxx(2) = 10
mxx(1) = 0: mxx(2) = 100
Select Case True
Case mxx(1) = nxx(1) And mxx(2) = nxx(2)
Debug.Print "运行1"
Case mxx(1) = nxx(1) And mxx(2) > nxx(2)
Debug.Print "运行2"
Case mxx(1) = nxx(1) And mxx(2) < nxx(2)
Debug.Print "运行3"
Case mxx(1) > nxx(1) And mxx(2) = nxx(2)
Debug.Print "运行4"
Case mxx(1) < nxx(1) And mxx(2) = nxx(2)
Debug.Print "运行5"
Case mxx(1) > nxx(1) And mxx(2) < nxx(2)
Debug.Print "运行6"
Case mxx(1) < nxx(1) And mxx(2) < nxx(2)
Debug.Print "运行7"
Case mxx(1) > nxx(1) And mxx(2) > nxx(2)
Debug.Print "运行8"
Case mxx(1) < nxx(1) And mxx(2) > nxx(2)
Debug.Print "运行9"
End Select
End Sub
【代码解析】
主要有两个变化
1.Select Case True不在此使用变量
2.每个Case分支使用一个And条件表达式
运行代码可以得到正确的结果。
更多推荐



所有评论(0)