基于动态列标题的条件格式数据透视表

时间:2019-07-16 02:41:41

标签: excel vba dynamic pivot-table conditional-formatting

感谢为VBA中的新手提供一些帮助和指导。
我正在尝试为数据透视表中的条件格式编写宏。

目标是按标题查找两列(因为它们的位置可能会发生变化),然后对其中之一应用条件公式。 (以红色突出显示异常值单元格)

标题在第3行中
以A

开头的列

以下示例:

我想找到包含起源机场的列,
然后找到具有原始处理的列,
 创建一个具有2个要比较的条件的公式,例如B4与B5(匹配)和D4与D5(匹配),然后突出显示原始处理(D列)中任何不符合要求的值,其中D4 <> D5。
我用来测试一致性的以下公式“ =(AND($ B4 = $ B5,D4 <> D5)”

! [表格截图](https://imgur.com/s6cQ08L

我在SO上浏览了各种帖子,并将我认为适用的代码放在一起。但是,作为一个新手,我没有得到正确的流程,试图逐段进行尝试,但是在尝试找到提供按查找列标题的列的代码时遇到了麻烦,然后创建了一个公式。下面的代码序列不完整。

    Sub Origin_Charges
        ' Review origin charges based on Consistency
        With ActiveSheet.PivotTables("Origin") 'focuses on the Pivot Table I named Origin'
            Dim ws as worksheet
            Dim rngDateHeader As Range
            Dim rngHeaders As Range
        End with

        Set rngHeaders = Range("3:3") 'Looks in entire first row; adjust as needed.
        Set rngDateHeader = rngHeaders.Find("Origin Airport")
            If rngDateHeader is Nothing then "No Origin Airport Column Found"

        Set rngHeaders = Range("3:3") 'Looks in entire first row; adjust as needed.
        Set rngDateHeader = rngHeaders.Find("Origin Handling")
            If rngDateHeader is Nothing then "No Origin Handling Column Found"

        Selection.FormatConditions.Add Type:=xlExpression, Formula1:= _
            "=AND($B4=$B5,D4<>D5)" 'Formula right now is fixed but want it to adjust based on what column Origin Airport is in'
        Selection.FormatConditions(Selection.
        FormatConditions.Count).SetFirstPriority
        With Selection.FormatConditions(1).Interior
            .PatternColorIndex = xlAutomatic
            .Color = 255
            .TintAndShade = 0
        End With

        With Sheets("Origin")
           .Range("D4").AutoFill .Range("D4:D" & .Cells(.Rows.count,"C")
           .End(xlUp).row)
        End With
    End Sub

非常感谢您的帮助。

1 个答案:

答案 0 :(得分:0)

您可以执行以下操作:

Dim c As Range, sht As Worksheet, f as string

Set sht = Activesheet

Set c = sht.Cells(4, rngDateHeader.Column) 'eg B4

f = "=AND(" & c.address(false, false) & "=" & _
     c.offset(1,0).address(false, false) & ",D4<>D5)"  '<< use formula f in your CF