下列程式碼範例會示範如何反白顯示作用中儲存格或是包含作用中儲存格的列和欄。 這些範例使用 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 擁有 25 年的業務管理和開發 Microsoft Office 應用程式的經驗,並共同編寫了《Holy Macro! It's 2,500 Excel VBA Examples》。
支援和意見反應
有關於 Office VBA 或這份文件的問題或意見反應嗎? 如需取得支援服務並提供意見反應的相關指導,請參閱 Office VBA 支援與意見反應。