Excel VBA 循环遍历数据透视项

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/24243034/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-08 18:20:11  来源:igfitidea点击:

Excel VBA loop through Pivot Items

excelvbaexcel-vbapivot

提问by Kathiieee

I want to loop through my pivot items and check if they exist in another table, see my Example Screenshot:

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

Example Pivot Table

示例数据透视表

So i want to loop through all the colors, checking if they exist in another table (e.g. in another sheet or so):

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

enter image description here

在此处输入图片说明

Is there any way to do this so there would appear a Message Box that the color purple was not found in the list?

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

Many thanks for your help!

非常感谢您的帮助!

回答by Rory

You can use something like this:

你可以使用这样的东西:

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