Excel_通过VBA高亮选择单元格的行列

在Excel里按ALT+F11,打开VBA面板,双击ThisWorkbook,在这里写的代码对所有excel有效

Public Sub Workbook_SheetSelectionChange(ByVal Sh As Object, ByVal Target As Range)
    Cells.FormatConditions.Delete '清除条件格式
    For Each Row In Target.Rows '遍历选择的行
    With Row.EntireRow.FormatConditions '行通过条件格式改变填充
         .Add xlExpression, , "TRUE"
         .Item(1).Interior.Color = RGB(217, 217, 217)
    End With
    Next
    For Each Col In Target.Columns '遍历选择的列
    With Col.EntireColumn.FormatConditions '列通过条件格式改变填充
        .Delete
        .Add xlExpression, , "TRUE"
        .Item(1).Interior.Color = RGB(217, 217, 217)
    End With
    Next
End Sub

方法名Workbook_SheetSelectionChange是固定写法,当任意工作表的选定区域变更时触发这个事件。

Excel_通过VBA高亮选择单元格的行列

效果

Excel_通过VBA高亮选择单元格的行列

Excel事件