重点内容
适用版本
桌面版通用(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: