设置Excel FormatConditions字体颜色运行时错误
在设置条件格式时,我在行上收到运行时错误“1004” .Font.color = vbRed
。 该Sub
在Excel 2011 for Mac上运行良好,但在Windows上失败。
我试着重新排列代码,使用RGB(255,0,0)
,设置.ColorIndex
,以及录制macros并使用该代码。 所有在Windows中失败。
如果单元格以“Med”开头,我试图将字体颜色设置为红色。 子从这里被调用:
Public Const BASE As String = "$D$14"
Dim cols As Long Dim rows As Long Dim applyToRange As Range Dim condition As String ' rows and cols variables set here... Set applyToRange = Range(BASE, Range(BASE).Offset(rows - 1, cols - 1)) ' Med condition = "Med" applyTextStringConditionals applyToRange, condition, xlBeginsWith, 0, False
我错过了什么?
Private Sub applyTextStringConditionals(ByVal applyToRange As Range, ByVal matchString As String, _ ByVal operator As Long, ByVal color As Long, ByVal stopIfTrue As Boolean) applyToRange.FormatConditions.Add Type:=xlTextString, String:=matchString, TextOperator:=operator applyToRange.FormatConditions(applyToRange.FormatConditions.Count).SetFirstPriority If color = 0 Then With applyToRange.FormatConditions(1) .Font.color = vbRed '<--- Error 1004 here '.TintAndShade = 0 End With Else applyToRange.FormatConditions(1).Interior.color = color End If applyToRange.FormatConditions(1).stopIfTrue = stopIfTrue End Sub
更新:
只有在创build了第一个条件格式的情况下,
Set applyToRange = Range(BASE, Range(BASE).Offset(rows - 12, cols - 1)) ' Med condition = "Med" Stop applyToRange.FormatConditions.Add Type:=xlTextString, String:=condition, TextOperator:=xlBeginsWith applyToRange.FormatConditions(applyToRange.FormatConditions.Count).SetFirstPriority applyToRange.FormatConditions(1).Font.Color = vbRed '-16776961 applyToRange.FormatConditions(1).stopIfTrue = True
但是这不是:
Private Sub applyTextStringConditionals(ByVal l_applyToRange As Range, ByVal matchString As String, _ ByVal l_Operator As Long, ByVal setColor As Long, ByVal l_stopIfTrue As Boolean) l_applyToRange.FormatConditions.Add Type:=xlTextString, String:=matchString, TextOperator:=l_Operator l_applyToRange.FormatConditions(l_applyToRange.FormatConditions.Count).SetFirstPriority If setColor = 0 Then l_applyToRange.FormatConditions.Item(1).Font.Color = vbRed Else l_applyToRange.FormatConditions(1).Interior.Color = setColor End If l_applyToRange.FormatConditions(1).stopIfTrue = True end sub