面對欄位眾多的寬表,橫向捲動查看單筆記錄極易「看走眼」(誤讀上/下列資料)。一段簡單的 VBA 事件程式碼,讓點選任一儲存格即自動高亮整列,再點一次取消,支援多列同時高亮,大幅提升查核效率。
Sheet1)。Sheet1 (Sheet1))。Private Sub Worksheet_SelectionChange(ByVal Target As Range)
If Target.CountLarge > 1 Then Exit Sub ' 多儲存格選取不處理
Static prevRow As Long
If prevRow <> 0 Then
Rows(prevRow).Interior.ColorIndex = xlNone ' 取消上一列高亮
End If
If Target.Row <> prevRow Then
Target.EntireRow.Interior.ColorIndex = 10 ' 色索引 10 = 綠色,可自行修改
prevRow = Target.Row
Else
prevRow = 0 ' 同列點兩次取消
End If
End Sub
| 程式碼片段 | 功能 | 可調整參數 |
|---|---|---|
Target.CountLarge > 1 | 忽略多儲存格選取(避免拖選時閃爍) | 若需支援多選可移除 |
ColorIndex = 10 | 高亮顏色(10=綠、6=黃、3=紅、37=淺藍) | 改為 RGB(255,255,0) 等自訂色 |
Static prevRow | 記住上一列,實現「點一下亮、再點一下熄」 | 若需多列同時亮,移除此變數與取消邏輯 |
Private Sub Worksheet_SelectionChange(ByVal Target As Range)
If Target.CountLarge > 1 Then
' 多選時:為所有涉及列加上高亮(不清除既有)
Dim r As Range
For Each r In Target.Rows
r.EntireRow.Interior.Color = RGB(200, 255, 200)
Next
Else
' 單選:切換該列高亮狀態
With Target.EntireRow.Interior
If .ColorIndex = 10 Then .ColorIndex = xlNone Else .ColorIndex = 10
End With
End If
End Sub
FormatConditions 動態增刪條件式格式規則以相容。SelectionChange 事件仍會觸發,但若鎖定儲存格不可選取則不會高亮。=ROW()=CELL("row") → 但需按 F9 重算才更新,非即時。