当您在查看包含大量数据的大型工作表时,如果 Excel 能自动高亮显示活动单元格的行和列,这样您就可以轻松读取数据并避免误读,那就太好了。以下是使用 VBA 代码高亮显示活动单元格区域的方法。
使用 Worksheet_SelectionChange 事件
示例一:高亮显示选择的单元格区域
当您在工作表上选择一个单元格区域时,该区域将立即以高亮显示的样式呈现,而之前的高亮显示将被清除,代码如下:

'-------------------- Sheet1 --------------------
Private Sub Worksheet_SelectionChange(ByVal Target As Range)
'清除上一次高亮显示的单元格区域
Cells.Interior.ColorIndex = xlColorIndexNone
'设置选择的单元格区域的背景色
Target.Interior.Color = RGB(255, 255, 0) ' 这里使用黄色作为示例
End Sub
注意
事件代码需要置于工作表对象里,例如 Sheet1
。
至少要选择两个以上的单元格才触发高亮选择区域时,代码如下:
'-------------------- Sheet1 --------------------
Private Sub Worksheet_SelectionChange(ByVal Target As Range)
' 清除上一次高亮显示的单元格区域
Cells.Interior.ColorIndex = xlColorIndexNone
' 检查是否选择了单元格区域
If Target.Cells.Count > 1 Then
' 设置选择的单元格区域的背景色
Target.Interior.Color = RGB(255, 255, 0) ' 这里使用黄色作为示例
End If
End Sub
示例二:高亮显示整行和整列
以下代码使用 Range 对象的 EntireRow 和 EntireColumn 属性来高亮显示整行和整列:

'------------------ Sheet1 ------------------
Private Sub Worksheet_SelectionChange(ByVal Target As Range)
On Error Resume Next
Application.ScreenUpdating = False
'清除上一次高亮显示的单元格区域
Cells.Interior.ColorIndex = 0
' 如果只选择了一个单元格则继续执行,否则退出过程
If Target.Cells.Count > 1 Then Exit Sub
With Target
' 高亮显示包含活动单元格的整个行和列
.EntireRow.Interior.ColorIndex = 6
.EntireColumn.Interior.ColorIndex = 6
End With
Application.ScreenUpdating = True
End Sub
示例三:高亮显示当前区域内的行和列
以下代码使用 Range 对象的 CurrentRegion 属性来高亮显示当前区域中包含活动单元格的行和列:

'------------------ Sheet1 ------------------
Private Sub Worksheet_SelectionChange(ByVal Target As Range)
On Error Resume Next
' 清除上一次高亮显示的单元格区域
Cells.Interior.ColorIndex = 0
' 如果活动单元格为空,或者选择了多个单元格则退出过程
If IsEmpty(Target) Or Target.Cells.Count > 1 Then Exit Sub
Application.ScreenUpdating = False
With ActiveCell
' 高亮显示当前区域内的行和列
Range(Cells(.Row, .CurrentRegion.Column), Cells(.Row, .CurrentRegion.Columns.Count + .CurrentRegion.Column - 1)).Interior.ColorIndex = 6
Range(Cells(.CurrentRegion.Row, .Column), Cells(.CurrentRegion.Rows.Count + .CurrentRegion.Row - 1, .Column)).Interior.ColorIndex = 6
End With
Application.ScreenUpdating = True
End Sub
使用 Worksheet_BeforeDoubleClick 事件
示例一:双击单元格高亮显示整行和整列
当您双击单元格时将高亮显示整行和整列:

'------------------ Sheet1 ------------------
Private Sub Worksheet_BeforeDoubleClick(ByVal Target As Range, Cancel As Boolean)
Dim strRange As String
strRange = Target.Cells.Address & "," & _
Target.Cells.EntireColumn.Address & "," & _
Target.Cells.EntireRow.Address
Range(strRange).Select
End Sub