我写了两个 VBA 子程序:
1) 设置条件格式(运算符、公式1和公式2可选)
Sub setConditionalFormatting(sheetName As String, cellRange As String, CFcellColor As String, CFfontColor As String, CFtype As XlFormatConditionType, Optional CFoperator As Variant, Optional CFformula1 As Variant, Optional CFformula2 As Variant)
On Error GoTo Errhandler
Dim sheet As Worksheet
Dim cell As range
Set sheet = Sheets(sheetName)
sheet.Select
Set cell = range(cellRange)
cell.Select
'user defined sub to print string in a file
Call OutputString("Setting Conditional Formatting...")
With cell.FormatConditions.Add( _
Type:=CFtype, _
Operator:=CFoperator, _
Formula1:=CFformula1, _
Formula2:=CFformula2)
.Interior.color = CFcellColor
.Font.color = CFfontColor
End With
Call OutputString("Conditional Formatting successfully applied")
Exit Sub
Errhandler:
'a sub for error handling task
Call ErrorHandler(Err)
Exit Sub
End Sub
2) 检查工作表上的条件格式 (CF) 并打印每个 CF 的属性:
Sub checkConditionalFormattingsOnSheet(sheetName As String, rng As String)
On Error GoTo Errhandler
Dim cellRange As range
Dim i As Integer
Dim temp As Variant
Sheets(sheetName).Select
Set cellRange = range(rng)
cellRange.Select
If cellRange.FormatConditions.Count > 0 Then
Call OutputString("Conditional formatting (CF) in sheet " + sheetName + ":")
For i = 1 To cellRange.FormatConditions.Count
Call OutputString(CStr(i) + ") Conditional Formatting-")
Call OutputString("Interior Color: " + CStr(cellRange.FormatConditions(i).Interior.color))
Call OutputString("Font Color: " + CStr(cellRange.FormatConditions(i).Font.color))
Call OutputString("CF Type: " + CStr(cellRange.FormatConditions(i).Type))
If IsMissing(cellRange.FormatConditions(i).Operator) Then
Call OutputString("CF Operator: Not Applicable")
Else
Call OutputString("CF Operator: " + CStr(cellRange.FormatConditions(i).Operator))
End If
Call OutputString("Formula1: " + CStr(cellRange.FormatConditions(i).Formula1))
If IsMissing(cellRange.FormatConditions(i).Formula2) Then
Call OutputString("CF Formula2: Not Applicable")
Else
Call OutputString("Formula2: " + CStr(cellRange.FormatConditions(i).Formula2))
End If
Next i
ElseIf cellRange.FormatConditions.Count = 0 Then
Call OutputString("No conditional formatting found in sheet " + sheetName)
End If
Exit Sub
Errhandler:
Call ErrorHandler(Err)
Exit Sub
End Sub
现在,当我想设置条件格式时,例如,“值大于 2 的单元格的单元格颜色应为 RGB(198,239,206),字体为 RGB(255,255,0)”,方法是调用函数
'PS: I am not parameterizing Optional value- Formula2 here
Call setConditionalFormatting( "MyWrkSheet", "C5:N13", RGB(198, 239, 206), RGB(255, 255, 0), xlCellValue, xlGreater, "=2")
我If IsMissing(cellRange.FormatConditions(i).Formula2)
在 checkConditionalFormattingsOnSheet 中遇到错误:
错误:应用程序定义或对象定义的错误 HelpContext:1000095,ErrorId:1004
我尝试了其他选项,例如“Is Nothing”、“IsNull()”以及将 Formula2 的参数分别传递为 Nothing 和 Null,但没有任何运气!
提前感谢您的时间和耐心!:)