Excel VBA循环通过数据透视表项

时间:2014-06-16 11:49:07

标签: excel vba excel-vba pivot

我想遍历我的数据透视表项并检查它们是否存在于另一个表中,请参阅我的示例屏幕截图:

Example Pivot Table

所以我想循环遍历所有颜色,检查它们是否存在于另一个表格中(例如在另一张表格中):

enter image description here

有没有办法这样做,所以会出现一个消息框,在列表中找不到紫色?

非常感谢你的帮助!

1 个答案:

答案 0 :(得分:6)

您可以使用以下内容:

Sub ListMissingItems()

    Dim pt As PivotTable
    Dim pf As PivotField
    Dim pi As PivotItem
    Dim rngList As Range
    Dim strMsg As String

    ' change sheet and range
    Set rngList = Worksheets("List").Range("A1:A10")

    Set pt = ActiveSheet.PivotTables(1)
    ' change field as needed
    Set pf = pt.PivotFields("Colour")

    For Each pi In pf.PivotItems
        If IsError(Application.Match(pi.Caption, rngList, 0)) Then strMsg = strMsg & vbLf & pi.Caption
    Next pi

    If Len(strMsg) > 0 Then MsgBox "The following items were not found in the list:" & strMsg
End Sub