设置Excel FormatConditions字体颜色运行时错误

时间:2017-04-18 03:20:23

标签: excel vba excel-vba runtime-error conditional-formatting

设置条件格式时,我在行.Font.color = vbRed上收到运行时错误“1004”。 Sub适用于Excel 2011 for Mac,但在Windows上失败。

我尝试使用RGB(255,0,0)重新排列代码,设置.ColorIndex,以及录制宏并使用该代码。所有窗户都失败了。

如果单元格以“Med”开头,我正在尝试将字体颜色设置为红色。从这里调用sub:

  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

更新

如果它是第一个创建的条件格式,则

 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

0 个答案:

没有答案