如何在ListObject(2)的隐藏行中高亮目标列?
问题:如何在ListObject(2)的隐藏行中高亮目标列?
现有VBA代码可在两个ListObject表格(ListObject(1)位于ListObject(2)正上方)中高亮选中单元格的对应行与列,同时清除所有隐藏行的着色,但目前隐藏行中的目标列无法被高亮。
原代码如下:
Sub Worksheet_SelectionChange(ByVal Target As Range) Dim oList1 As ListObject Dim oList2 As ListObject Dim rng As Range Set oList1 = Me.ListObjects(1) ' 应用筛选后会包含隐藏行 Set oList2 = Me.ListObjects(2) ' 仅当选中区域在ListObject(2)的数据区域内时执行后续逻辑 If Intersect(Target, oList2.DataBodyRange) Is Nothing Then Exit Sub Application.ScreenUpdating = False ' 清除所有单元格的填充色 Me.Cells.Interior.ColorIndex = 0 ' 高亮ListObject(1)中目标列的数据区域 Set rng = Intersect(Target.EntireColumn, oList1.DataBodyRange) If Not rng Is Nothing Then rng.Interior.ColorIndex = 24 End If ' 高亮ListObject(2)中目标列的数据区域 Set rng = Intersect(Target.EntireColumn, oList2.DataBodyRange) rng.Interior.ColorIndex = 24 ' 高亮ListObject(2)中目标行的数据区域 Set rng = Intersect(Target.EntireRow, oList2.DataBodyRange) rng.Interior.ColorIndex = 38 ' 清除所有隐藏行的着色 For Each oRow In oList2.ListRows If oRow.Range.EntireRow.Hidden Then oRow.Range.Interior.ColorIndex = 0 End If Next oRow Application.ScreenUpdating = True End Sub
尝试与问题
尝试在清除隐藏行着色后,重新为隐藏行中的目标列着色,但出现运行时错误'91':对象变量或With块变量未设置,尝试的代码片段如下:
Dim oCol As ListColumn ' 清除隐藏行着色并重新为隐藏行的目标列着色 For Each oRow In oList2.ListRows If oRow.Range.EntireRow.Hidden Then With Target oCol.Range.Interior.ColorIndex = 24 End With End If Next oRow
解决方案
错误原因是代码中声明了oCol但未给它赋值,导致引用oCol.Range时触发对象未设置的错误。正确的做法是:遍历隐藏行时,找到该行中与选中单元格(Target)同列的单元格,再设置其填充色。
修改后的完整代码如下:
Sub Worksheet_SelectionChange(ByVal Target As Range) Dim oList1 As ListObject Dim oList2 As ListObject Dim rng As Range Dim oRow As ListRow Dim targetColInList2 As Long Set oList1 = Me.ListObjects(1) Set oList2 = Me.ListObjects(2) ' 仅当选中区域在ListObject(2)的数据区域内时执行后续逻辑 If Intersect(Target, oList2.DataBodyRange) Is Nothing Then Exit Sub Application.ScreenUpdating = False ' 清除所有单元格的填充色 Me.Cells.Interior.ColorIndex = 0 ' 高亮ListObject(1)中目标列的数据区域 Set rng = Intersect(Target.EntireColumn, oList1.DataBodyRange) If Not rng Is Nothing Then rng.Interior.ColorIndex = 24 End If ' 高亮ListObject(2)中目标列的数据区域 Set rng = Intersect(Target.EntireColumn, oList2.DataBodyRange) rng.Interior.ColorIndex = 24 ' 高亮ListObject(2)中目标行的数据区域 Set rng = Intersect(Target.EntireRow, oList2.DataBodyRange) rng.Interior.ColorIndex = 38 ' 获取Target在ListObject(2)中的相对列索引 targetColInList2 = Target.Column - oList2.Range.Column + 1 ' 处理隐藏行:先清除整行着色,再单独高亮目标列 For Each oRow In oList2.ListRows If oRow.Range.EntireRow.Hidden Then ' 清除隐藏行的所有着色 oRow.Range.Interior.ColorIndex = 0 ' 高亮该行中的目标列单元格 oRow.Range.Cells(1, targetColInList2).Interior.ColorIndex = 24 End If Next oRow Application.ScreenUpdating = True End Sub
关键修改点:
- 新增
targetColInList2变量,计算选中单元格在ListObject(2)中的相对列索引,避免直接使用工作表列号导致的错位。 - 遍历隐藏行时,先清除整行着色,再通过
oRow.Range.Cells(1, targetColInList2)定位到该行的目标列单元格,设置填充色。 - 移除未赋值的
oCol变量,避免对象未设置的错误。
内容的提问来源于stack exchange,提问作者Mohamad Bachrouche
相关产品推荐
相关产品推荐

