选中活动单元格、行或列
以下代码示例显示了多种选中活动单元格或包含活动单元格的行和列的方式。 以下示例使用 Worksheet 对象的 SelectionChange 事件。
示例代码提供者:Tom Urtis,Atlas Programming Management
选中活动单元格
以下示例代码通过将 ColorIndex 属性设为等于 0 来清除工作表上的所有单元格中的颜色,然后通过将 ColorIndex 属性设为等于 8(青绿色)来选中活动单元格。
Private Sub Worksheet_SelectionChange(ByVal Target As Range)
Application.ScreenUpdating = False
' Clear the color of all the cells
Cells.Interior.ColorIndex = 0
' Highlight the active cell
Target.Interior.ColorIndex = 8
Application.ScreenUpdating = True
End Sub
选中包含活动单元格的整行和整列。
以下示例代码通过将 ColorIndex 属性设为等于 0 来清除工作表上的所有单元格中的颜色,然后通过使用 EntireRow 和 EntireColumn 属性选中包含活动单元格的整行和整列。
Private Sub Worksheet_SelectionChange(ByVal Target As Range)
If Target.Cells.Count > 1 Then Exit Sub
Application.ScreenUpdating = False
' Clear the color of all the cells
Cells.Interior.ColorIndex = 0
With Target
' Highlight the entire row and column that contain the active cell
.EntireRow.Interior.ColorIndex = 8
.EntireColumn.Interior.ColorIndex = 8
End With
Application.ScreenUpdating = True
End Sub
选中当前区域内包含活动单元格的行和列
以下代码示例通过将 ColorIndex 属性设为等于 0 来清除工作表上的所有单元中的颜色,然后通过使用 Range 对象的 CurrentRegion 属性来选中当前区域内包含活动单元格的行和列。
Private Sub Worksheet_SelectionChange(ByVal Target As Range)
' Clear the color of all the cells
Cells.Interior.ColorIndex = 0
If IsEmpty(Target) Or Target.Cells.Count > 1 Then Exit Sub
Application.ScreenUpdating = False
With ActiveCell
' Highlight the row and column that contain the active cell, within the current region
Range(Cells(.Row, .CurrentRegion.Column), Cells(.Row, .CurrentRegion.Columns.Count + .CurrentRegion.Column - 1)).Interior.ColorIndex = 8
Range(Cells(.CurrentRegion.Row, .Column), Cells(.CurrentRegion.Rows.Count + .CurrentRegion.Row - 1, .Column)).Interior.ColorIndex = 8
End With
Application.ScreenUpdating = True
End Sub
关于参与者
MVP Tom Urtis 是 Atlas Programming Management 的创始人,这是一家位于硅谷的全服务型 Microsoft Office 和 Excel 业务解决方案公司。 Tom 在业务管理和 Microsoft Office 应用程序开发方面拥有 25 年以上的经验,与他人合著过“Holy Macro! It's 2,500 Excel VBA Examples”(Holy Macro! 2,500 个 Excel VBA 示例)。
支持和反馈
有关于 Office VBA 或本文档的疑问或反馈? 请参阅 Office VBA 支持和反馈,获取有关如何接收支持和提供反馈的指南。
反馈
https://aka.ms/ContentUserFeedback。
即将推出:在整个 2024 年,我们将逐步取消以“GitHub 问题”作为内容的反馈机制,并将其替换为新的反馈系统。 有关详细信息,请参阅:提交和查看相关反馈