Setting Excel FormatConditions Font Color Run-time Error

扶醉桌前 提交于 2019-12-24 10:57:12

问题


I am receiving a run-time error '1004' on the line .Font.color = vbRed when setting conditional formats. The Sub works great on Excel 2011 for Mac, but fails on Windows.

I've tried rearranging the code, using RGB(255,0,0), setting .ColorIndex, as well as recording a macro and using that code. All failed in windows.

I'm trying to set the font color to red if the cell begins with "Med". The sub is called from here:

  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

What am I missing?

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

UPDATE:

This works, only if it's the first conditional format created:

 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

But this does not:

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

来源:https://stackoverflow.com/questions/43463037/setting-excel-formatconditions-font-color-run-time-error

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!