Microsoft Lab
全部软件
Excel条件判断(If Then Statement)约 5 分钟

Select Case Select Case 结构

重点内容


适用版本

桌面版通用(Excel 365 / 2021 / 2019 等)。


案例一:用比较运算符分级

场景:A1 输入分数,B1 输出评级。

Dim score As Integer, result As String
score = Range("A1").Value

Select Case score
    Case Is >= 80
        result = "very good"
    Case Is >= 70
        result = "good"
    Case Is >= 60
        result = "sufficient"
    Case Else
        result = "insufficient"
End Select

Range("B1").Value = result

用比较运算符(Is >= 80)时 VBA 会自动加上 Is 这个关键字。VBA 按顺序往下测试,比如分数落在 70-79 之间,会命中第二个 Case Is >= 70 就结束判断,不会继续往下比对。


案例二:用 To 区间和精确匹配值

场景:判断某个数字落在哪个范围内,或是否等于特定值。

Dim number As Integer, result As String
number = Range("A1").Value

Select Case number
    Case 1 To 10
        result = "Number between 1 and 10"
    Case 11
        result = "Number equal to 11"
    Case 12 To 17
        result = "Number between 12 and 17"
    Case 18, 19, 20
        result = "Number equal to 18, 19 or 20"
    Case Else
        result = "Number not between 1 and 20"
End Select

Range("B1").Value = result

Case 1 To 10 是区间写法,Case 18, 19, 20 是用逗号列出多个精确值,两种写法可以混用在同一个 Select Case 结构里。Case Else 永远是可选的,用来接住前面所有条件都没命中的情况。


方法怎么选

情境用哪个备注
同一个变量要对比很多种情况(3 个分支以上)Select Case比一长串 If Then ElseIf 更清楚好读
分支条件涉及多个不同变量、或判断逻辑本身复杂If ThenSelect Case 只针对同一个变量做比较,跨变量判断要用 If Then

怎么运行

Alt+F11 打开 VBA 编辑器,把代码放进模块或按钮点击事件,按 F5 或点命令按钮执行,结果写入 B1。


学完你会

常见错误

  • 用比较运算符时漏写 Is 关键字(虽然 VBA 常会自动补上,手写时最好养成习惯自己带上)
  • Case 的判断顺序会影响结果,条件区间有重叠时,只有第一个命中的 Case 会执行,后面的会被跳过——顺序要从严格到宽松排列,否则宽松条件会抢先命中
  • 忘记加 Case Else,遇到没预期到的输入值时程序不会报错,但也不会有任何结果写入

Sources

Blog / Website:

  1. Select Case
只记在你的浏览器里,换设备不会同步。