Microsoft Lab
全部软件
Excel范围对象(Range Object)约 3 分钟

Test a Selection 检验选取内容

重点内容


适用版本

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


完整代码

Dim rng As Range, cell As Range

Set rng = Range("C4:D10")
Set cell = Selection

If cell.Count = 1 And IsNumeric(cell) And Not IsEmpty(cell) And Not Intersect(rng, cell) Is Nothing Then
    MsgBox "You win"
Else
    MsgBox "You lose"
End If

逻辑说明

四个条件全部满足才算「赢」:

  • cell.Count = 1:只选中一个单元格(不是一整片范围)
  • IsNumeric(cell):内容是数字
  • Not IsEmpty(cell):不是空格
  • Not Intersect(rng, cell) Is Nothing:这一格确实落在 C4:D10 这个指定范围内(Intersect 有交集才不是 Nothing)

学完你会

常见错误

  • 判断条件漏了其中一项,比如没检查 cell.Count = 1,选中一整片范围时逻辑也会误判
  • Intersect 返回 Nothing 时忘记加 Not ... Is Nothing 判断,直接当成一般条件式使用会出错
  • 把好几个条件用 Or 串起来而不是 And,只要满足其中一个就通过,跟原本想要「同时成立」的需求不符

Sources

Blog / Website:

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