You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

VBA中If语句内Or逻辑判断不生效问题咨询

VBA逻辑判断问题解析:Or运算符误用导致的错误

你原代码的问题出在逻辑运算符使用错误,把本该用And的地方写成了Or,导致条件永远为真,Else分支根本不会执行。

原代码错误分析

原条件:

If Cells(i, iCol).Value <> "0" Or Cells(i, iCol).Value <> vbNullString Then

不管单元格里的值是什么,这个条件都会成立:

  • 若值是"0",<> vbNullString为真,整个Or条件为真;
  • 若值是空字符串(vbNullString),<> "0"为真,整个Or条件为真;
  • 若值是其他内容,两个子条件都为真,Or条件自然也为真。

所以循环里永远执行Cells(i, iCol).EntireRow.Hidden = False,所有行都不会被隐藏,和你想要的效果完全相反。

正确逻辑的If写法

把Or改成And,就能实现和Select Case一样的效果:

Dim StartRow As Long
Dim LastRow As Long
Dim iCol As Long
Dim i As Long

For i = StartRow To LastRow
    If Cells(i, iCol).Value <> "0" And _
    Cells(i, iCol).Value <> vbNullString Then
        ' 既不是0也不是空,显示行
        Cells(i, iCol).EntireRow.Hidden = False
    Else
        ' 是0或者空,隐藏行
        Cells(i, iCol).EntireRow.Hidden = True
    End If
Next i

替代的Select Case逻辑为什么正确

你用的Select Case写法:

Select Case Cells(i, iCol).Value
    Case vbNullString, "0"
        Cells(i, iCol).EntireRow.Hidden = True
    Case Else
        ' do nothing
End Select

直接明确指定了「值为空或0时隐藏行」,逻辑清晰且正确,所以能正常运行。

内容的提问来源于stack exchange,提问作者nussbaumer05

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.23 10:52:48