VBA条件格式公式中的引用不起作用

时间:2018-01-25 23:26:36

标签: excel-vba vba excel

这是一个更大代码的片段。我有以下代码,我试图在活动列可以更改的单元格范围内插入条件格式。我希望条件格式公式在活动列更改时更新。 f1 = "=IF(AND(MID(CTO_1,6,1)=""W"",NOT(ISBLANK(RC[-7]))),RC12<>RC19,RC11<>RC19)"&#39;这是正常的,但当我尝试将其修改为动态时,它无法正常工作。

我花了很多时间寻找没有运气的解决方案

Private Sub test()

Worksheets("C9 map").Activate

Dim lstCol, lstRow, nCol As Integer
Dim cRng3, cRng2, cRng1, strRow As Variant

lstCol = LastRowColumn("c") ' function to find last column
lstRow = LastRowColumn("r") ' function to find last row

nCol = lstCol + 1

strRow = 5

Range(Columns(nCol).Rows(strRow), Columns(nCol).Rows(strRow)).Activate

Dim actCol, hdrRow5 As Variant

actCol = ActiveCell.Column

Dim f1 As String

hdrRow5 = 5
cRng1 = "RC" & 11 'Column K = 11
cRng2 = "RC" & 12 'Column L = 12
cRng3 = "RC" & ActiveCell.Column

f1 = "=IF(AND(MID(CTO_1,6,1)=""W"",NOT(ISBLANK(RC[-7]))),cRng2<>cRng3,cRng1<>cRng3)"

With Columns(actCol)
    .ColumnWidth = 20
    .HorizontalAlignment = xlCenter
    .WrapText = True
End With
With Range(Columns(actCol).Rows(hdrRow5), Columns(actCol).Rows(lstRow))
    .FormatConditions.Add Type:=xlExpression, Formula1:=f1


        With .FormatConditions(1).Font
            .Bold = True
            .Italic = False
            .Color = -16776961
            .TintAndShade = 0
        End With
        With .FormatConditions(1).Interior
            .PatternColorIndex = xlAutomatic
            .Color = 65535
            .TintAndShade = 0
        End With
        .FormatConditions(1).StopIfTrue = False
End With

End Sub

1 个答案:

答案 0 :(得分:0)

问题来自于您的cRng1,cRng2和cRng3在代码中以字符串形式提供,因为&#34;&#34;

将您的行更改为:

f1 = "=IF(AND(MID(CTO_1,6,1)=""W"",NOT(ISBLANK(RC[-7])))," & cRng2 & "<>" & cRng3 & "," & cRng1 & "<>" & cRng3 & ")"