IT编程技术

天行健,君子以自强不息;地势坤,君子以厚德载物;

Excel VBA第九节-Select Case语句

2020-12-25 博主:Splendor EXCEL VBA基础

Select Case语句
select case同样也是流程控制语句,相当你站在多条路的路口,你在摇色子,根据你摇色子结果而决定未来选择要走哪条路,有的朋友会想有了if不就够用了吗,为什么还要这个语句。万事万物存在必有存在的道理。
lu.jpg
语法:
Select Case 测试表达式
Case 表达式1
如果表达式1匹配测试表达式的语句
Case 表达式2
如果表达式2匹配测试表达式的语句
Case 表达式N
如果表达式N匹配测试表达式的语句
Case Else
如果没有表达式匹配测试表达式要执行的语句
End Select

请看下面的if代码(你会发现阅读会困难,语句也特别多):
If Range("A3") >= 90 Then
    MsgBox "You got an A on the test! "
ElseIf Range("A3") <90 And Range("A3") >= 80 Then
    MsgBox "You got a B on the test. "
ElseIf Range("A3") <80 And Range("A3") >= 70 Then
    MsgBox "You got a C on the test. "
ElseIf Range("A3") < 70 And Range("A3") >= 60 Then
    MsgBox "You got a D on the test. "
Else
    MsgBox "You failed. "
End If

再请看select语句改写的上面的代码(你会发现整个过程清晰明了,同时也减少了很多代码量):
Select Case Range("A3")
     Case Is >= 90
        MsgBox "You got an A on the test. "
     Case 80 To 89
        MsgBox "You got a B on the test. "
     Case 70 To 79
        MsgBox "You got a C on the test. "
     Case 60 To 69
        MsgBox "You got a D on the test. "
     Case Else
        MsgBox "You failed. "
End Select

总结:什么情况用select case最好,当你的条件有多个情况需要改变程序运行方向时,用select case语句会更好。

标签: EXCELVBA基础