需要在同环比列设置条件格式,低于大盘的数值应显示为红色。总共需要对4列/表 * 16张表 = 64个条件进行设置。

示例图片

每次设置条件格式都需要进行一系列步骤,例如选择”条件格式”,然后选择”突出显示单元格规则”,再选择”小于”,最后选择字体颜色等。这些步骤非常繁琐,而且使用格式刷也无法实现。因此,选择使用 VBA 实现条件格式设置:”在一个选区中,小于该列最后一个数字的数值应显示为红色”。以下是相应的代码:

Sub SetConditionalFormat()
Dim rng As Range
Dim col As Long
Dim lastVal As Variant

' 获取已选定的范围
Set rng = Selection

' 遍历每一列
For col = 1 To rng.Columns.Count
' 获取每列最后一个单元格的数值
lastVal = rng.Cells(rng.Rows.Count, col).Value

' 如果是数字,则设置条件格式
If IsNumeric(lastVal) Then
' 添加条件格式规则:如果小于最后一个数值,则设置字体为红色
rng.Columns(col).FormatConditions.Add Type:=xlCellValue, Operator:=xlLess, Formula1:=lastVal
rng.Columns(col).FormatConditions(1).Font.Color = vbRed
End If
Next col
End Sub

示例图片

通过运行上述 VBA 代码,可以快速设置条件格式。只需要选定要设置条件格式的区域,然后运行该宏即可,非常节省时间。然而,如果需要设置多个区域的条件格式,仍然需要选定每个区域进行设置,这仍然有些繁琐。

考虑到每张表的表头是相似的,只需要在第9、12、15、18列应用条件格式。以下是优化后的版本:

Sub SetConditionalFormat()
Dim rng As Range
Dim col As Variant
Dim lastVal As Variant

' 获取已选定的范围
Set rng = Selection

' 定义一个数组,存储要设置条件格式的列号
Dim colsArray(1 To 4) As Variant
colsArray(1) = 9
colsArray(2) = 12
colsArray(3) = 15
colsArray(4) = 18

' 遍历数组中的每个列号
For Each col In colsArray
' 获取每列最后一个单元格的数值
lastVal = rng.Cells(rng.Rows.Count, col).Value

' 如果是数字,则设置条件格式
If IsNumeric(lastVal) Then
' 添加条件格式规则:如果小于最后一个数值,则设置字体为红色
rng.Columns(col).FormatConditions.Add Type:=xlCellValue, Operator:=xlLess, Formula1:=lastVal
rng.Columns(col).FormatConditions(1).Font.Color = vbRed
End If
Next col
End Sub

示例图片

这样一来,只需要选定16个区域即可。