VBA 中的目标条件格式
Targeted Conditional Formatting in VBA
我有一个包含 15 列数据的 Excel sheet。我想检查其中一列,并突出显示小于 25,000,000 的单元格。只要录制一个宏我就可以做到,它给了我这个代码:
Sub ebitda_check()
'ebitda < 25MM Macro
Columns("H:H").Select
Selection.FormatConditions.Add Type:=xlCellValue, Operator:=xlLess, _
Formula1:="=25000000"
Selection.FormatConditions(Selection.FormatConditions.Count).SetFirstPriority
With Selection.FormatConditions(1).Interior
.PatternColorIndex = xlAutomatic
.Color = 255
.TintAndShade = 0
End With
Selection.FormatConditions(1).StopIfTrue = False
End Sub
但这并不能说明我要定位的列下次可能会四处移动或位于不同的列中。我怎样才能写一些东西来检查,例如 "if the column header is 'EBITDA', highlight anything under 25,000,000"?
像这样:
Sub ebitda_check()
Dim f As Range, sht As Worksheet, rng As Range
Set sht = ActiveSheet
'find the header
Set f = sht.Rows(1).Find("EBITDA", lookat:=xlWhole)
'if found, format the content below the header
If Not f Is Nothing Then
Set rng = sht.Range(f.Offset(1, 0), sht.Cells(Rows.Count, f.Column).End(xlUp))
With rng.FormatConditions.Add(Type:=xlCellValue, Operator:=xlLess, _
Formula1:="=25000000")
.SetFirstPriority
With .Interior
.PatternColorIndex = xlAutomatic
.Color = 255
.TintAndShade = 0
End With
.StopIfTrue = False
End With
End If
End Sub
我有一个包含 15 列数据的 Excel sheet。我想检查其中一列,并突出显示小于 25,000,000 的单元格。只要录制一个宏我就可以做到,它给了我这个代码:
Sub ebitda_check()
'ebitda < 25MM Macro
Columns("H:H").Select
Selection.FormatConditions.Add Type:=xlCellValue, Operator:=xlLess, _
Formula1:="=25000000"
Selection.FormatConditions(Selection.FormatConditions.Count).SetFirstPriority
With Selection.FormatConditions(1).Interior
.PatternColorIndex = xlAutomatic
.Color = 255
.TintAndShade = 0
End With
Selection.FormatConditions(1).StopIfTrue = False
End Sub
但这并不能说明我要定位的列下次可能会四处移动或位于不同的列中。我怎样才能写一些东西来检查,例如 "if the column header is 'EBITDA', highlight anything under 25,000,000"?
像这样:
Sub ebitda_check()
Dim f As Range, sht As Worksheet, rng As Range
Set sht = ActiveSheet
'find the header
Set f = sht.Rows(1).Find("EBITDA", lookat:=xlWhole)
'if found, format the content below the header
If Not f Is Nothing Then
Set rng = sht.Range(f.Offset(1, 0), sht.Cells(Rows.Count, f.Column).End(xlUp))
With rng.FormatConditions.Add(Type:=xlCellValue, Operator:=xlLess, _
Formula1:="=25000000")
.SetFirstPriority
With .Interior
.PatternColorIndex = xlAutomatic
.Color = 255
.TintAndShade = 0
End With
.StopIfTrue = False
End With
End If
End Sub