条件格式公式1中的变量

时间:2014-08-15 02:17:48

标签: excel excel-vba vba

我正在尝试在FormatCondition Formula1属性中使用变量。变量将是单元格引用。但是,我无法正确使用语法。我在下面的代码中遇到问题的两个位是:"=(C$3:J$10=""CM"")""=($C3:$J10=""RM"")"

这样做的目的是在某个单元格中突出显示具有CM的列,并在某个单元格中突出显示具有RM的行。列数和行数将增加和减少,因此使用变量。

或者,如果这不是正确的方式或最佳方式,我们将不胜感激。

代码是:

Private Sub Workbook_Open()
Application.ScreenUpdating = False
'Rows
Dim iRowA As Integer, iRowB As Integer, iRowC As Integer
Dim iRowDataStart As Integer, iRowLast As Integer
'Columns
Dim iColX As Integer, iColY As Integer, iColZ As Integer
Dim iColDataStart As Integer, iColLast As Integer
'Ranges
Dim rAll As Range
Dim rRowB As Range, rColY As Range
Dim rRowMark As Range, rColMark As Range
'String
Dim sString As String
'Assign values, normally these would be variable values, not assigned
iRowA = 1: iRowB = 2: iRowC = 3
iRowDataStart = 4: iRowLast = 10
iColX = 1: iColY = 2: iColZ = 3
iColDataStart = 4: iColLast = 10
'Set ranges
Set rAll = Range(Cells(iRowA, iColX), Cells(iRowLast, iColLast))
Set rRowB = Range(Cells(iRowB, iColZ), Cells(iRowLast, iColLast))
Set rColY = Range(Cells(iRowC, iColY), Cells(iRowLast, iColLast))
Set rRowMark = Range(Cells(iRowC, iColZ), Cells(iRowLast, iColLast))
Set rColMark = Range(Cells(iRowC, iColZ), Cells(iRowLast, iColLast))
'Delete all CF currently in the worksheet
With rAll
    .FormatConditions.Delete
End With
'Format column with Column Mark
sString = "=(C$3:J$10=""CM"")"
With rRowB
    .FormatConditions.Add _
        Type:=xlExpression, _
        Formula1:=sString
    .FormatConditions(.FormatConditions.Count).SetFirstPriority
    With .FormatConditions(1)
        .Interior.Color = RGB(196, 189, 151)
        .StopIfTrue = False
    End With
End With
'Format row with Row Mark
sString = "=($C3:$J10=""RM"")"
With rColY
    .FormatConditions.Add _
        Type:=xlExpression, _
        Formula1:=sString
    .FormatConditions(.FormatConditions.Count).SetFirstPriority
    With .FormatConditions(1)
        .Font.ColorIndex = 2
        .Interior.Color = RGB(127, 127, 127)
        .StopIfTrue = False
    End With
End With
Range("A1").Select
Application.StatusBar = False
Application.CutCopyMode = False
End Sub

1 个答案:

答案 0 :(得分:0)

您只需要通过获取数据的最后一行和哪一列来动态设置范围,您可以在此处找到许多示例like this one。类似的东西:

Dim r As Range
Dim lr As Long, lc As Long
Dim formula As String

With Sheet1 '~~> change to your actual sheet
    lr = .Range("C" & .Rows.Count).End(xlUp).Row '~~> based on C, adjust to suit
    lc = .Cells(3, .Columns.Count).End(xlToLeft).Column '~~> based on row 3
    Set r = .Range(.Cells(3, 3), .Cells(lr, lc))
    formula = "=(" & r.Address & "=""CM"")"
    '~~> formatting code here
End With

或者您可以尝试我在此处发布的关于Conditional Formatting的内容,当我发布HEREHERE时,这当然可以自动生成。类似的东西:

formula = "=C3=""CM"""
[C3].FormatConditions.Add xlExpression, , formula
With [C3].FormatConditions(1)
    .Interior.Color = RGB(196, 189, 151)
    .ModifyAppliesToRange r
End With

HTH。