突出显示数据透视表中组的相同列的差异

时间:2016-04-12 16:14:15

标签: excel excel-vba excel-formula vba

我创建了一个包含A列和B列的数据透视表。 A列与B列有一对多的关系。

如果其范围中的B列值存在差异,我想要突出显示A列。例如,

A            B
ABC          10
             10
XYZ          20
             25

在这种情况下,XYZ在B列中有2个不同的值。我想强调一下。如何在excel中完成?

干杯!!

1 个答案:

答案 0 :(得分:1)

以下是使用VBA进行操作的方法

Private Sub CommandButton8_Click()
Dim WS As Excel.Worksheet
Dim lRow As Long
Dim lastRow As Long
Dim ValueB As String
Dim lRowA As Long

    Set WS = Application.Sheets("Sheet1")
    lRow = 1

    'Get the last row that has data in columnB
    lastRow = WS.Cells(WS.Rows.Count, "B").End(xlUp).Row

    'Loop through all the rows
    Do While lRow <= lastRow

        'If we have data in columnA, record it
        If WS.Range("A" & lRow).Value <> "" Then
            ValueB = WS.Range("B" & lRow).Value
            'Keep track of the row that we found new columnA data on
            lRowA = lRow
        Else
            'We don't have data in columnA, Compare what we found in 
            'columnB of the last row where we had data in columnA with this row
            If ValueB <> WS.Range("B" & lRow).Value Then
                WS.Range("A" & lRowA).Interior.Pattern = xlSolid
                WS.Range("A" & lRowA).Interior.PatternColorIndex = xlAutomatic
                WS.Range("A" & lRowA).Interior.Color = 255
            End If
        End If

        lRow = lRow + 1
        WS.Range("A" & lRow).Activate
    Loop

End Sub