VBA如何实现仅选中O、P列均为PASS的对应J列单元格区域
问题描述
我在O6:P区域设置了两列判定规则,用于校验J列对应行的数据,校验结果展示为Pass或Fail。O列与P列的判定结果并非始终一致,可能出现一列显示Pass、另一列显示Fail的情况。
现有代码大部分场景可正常运行,但当前逻辑会选中O列或P列任意一列为PASS的对应J列区域,需要调整为仅选中O、P两列同一行均为Pass的对应J列区域。
原有代码如下:
Dim lastrow As Long Dim xRg As Range, yRg As Range, nRg As Range, mRg As Range 'Selecting range = to PASS With ShNC1 lastrow = .Cells(.Rows.Count, "J").End(xlUp).Row Application.ScreenUpdating = False For Each xRg In .Range("O6:P" & lastrow) If UCase(xRg.Text) = "PASS" Then If yRg Is Nothing Then Set yRg = .Range("J" & xRg.Row) Else Set yRg = Union(yRg, .Range("J" & xRg.Row)) End If End If Next xRg End With If Not yRg Is Nothing Then yRg.Select
问题原因
原有代码逐单元格遍历O、P两列的所有内容,只要任意一个单元格匹配PASS就会把对应行的J列加入选中范围,执行的是或逻辑判断,和需要的「同列双Pass才选中」的与逻辑要求不匹配,同时还存在重复加入同一行J列的可能(比如某行O、P都是PASS时,会被两次加入Union范围)。
调整后代码
Dim lastrow As Long Dim yRg As Range Dim i As Long With ShNC1 lastrow = .Cells(.Rows.Count, "J").End(xlUp).Row Application.ScreenUpdating = False ' 从第6行开始逐行遍历所有数据行 For i = 6 To lastrow ' 同时校验当前行O、P两列值,均为PASS时才选中对应J列 If UCase(.Range("O" & i).Text) = "PASS" And UCase(.Range("P" & i).Text) = "PASS" Then If yRg Is Nothing Then Set yRg = .Range("J" & i) Else Set yRg = Union(yRg, .Range("J" & i)) End If End If Next i End With ' 选中符合条件的区域,恢复屏幕更新 If Not yRg Is Nothing Then yRg.Select Application.ScreenUpdating = True
核心调整点
- 遍历逻辑从逐单元格遍历O:P区域,改为按行号逐行遍历,避免同一行被重复判断
- 判断条件用
And连接O列、P列的PASS校验,只有两个条件同时满足时才将对应J列加入选中范围 - 补充
ScreenUpdating = True语句,避免代码运行后Excel屏幕刷新被异常关闭 - 移除了原代码中声明后未使用的多余变量,精简代码结构
内容的提问来源于stack exchange,提问作者CRS.
相关产品推荐
相关产品推荐

