简体   繁体   English

如何在 VBA 中使用循环遍历数据透视表的嵌套 for 循环?

[英]How to use nested for loop that loops through pivot tables in VBA?

I am trying to use a nested for loop that parses through all the worksheets (1st For Loop) and parses through each Pivot table in each worsksheets (2nd For loop).我正在尝试使用嵌套的 for 循环来解析所有工作表(第一个 For 循环)并解析每个工作表中的每个数据透视表(第二个 For 循环)。 Within 2nd For loop, I am trying to change the pivot filter value based on a combobox selection.在第二个 For 循环中,我试图根据组合框选择更改枢轴过滤器值。

Below is the code, but it does not loop through the 2nd for loop.下面是代码,但它不会遍历第二个 for 循环。


Private Sub bo_combobox_Change()
Dim a As String
Dim pt As PivotTable
Dim ws As Worksheet

    If bo_combobox.Value <> "" Then       

        For Each ws In ActiveWorkbook.Worksheets

            For Each pt In ThisWorkbook.PivotTables
                With pt.PivotFields("Objective")
                    .ClearAllFilters
                    .CurrentPage = bo_combobox.Value
                    Debug.Print (.CurrentPage)
                End With
            Next pt

        Next ws

    End If   

End Sub

Your (asked about) problem is with你(被问到)的问题是

For Each pt In ThisWorkbook.PivotTables

The Workbook.PivotTables collection is not what it seems: Workbook.PivotTables集合并不是它看起来的样子:

From the documentation文档

The PivotTables property of the Workbook object does not return all the PivotTable objects in the workbook; Workbook 对象的 PivotTables 属性不会返回工作簿中的所有 PivotTable 对象; instead, it returns only those associated with decoupled PivotCharts.相反,它仅返回与解耦数据透视图关联的数据。 However, the PivotTables method of the Worksheet object returns all the PivotTable objects on the worksheet, irrespective of whether they are associated with decoupled PivotCharts.但是,Worksheet 对象的 PivotTables 方法返回工作表上的所有 PivotTable 对象,而不管它们是否与解耦的 PivotCharts 相关联。

That said, there are several other issues也就是说,还有其他几个问题

  1. You have For Each ws In ActiveWorkbook.Worksheets then don't use wsFor Each ws In ActiveWorkbook.WorksheetsFor Each ws In ActiveWorkbook.Worksheets然后不要使用ws
  2. You are referenceing both ActiveWorkbook and ThisWorkbook .您正在引用ActiveWorkbookThisWorkbook These may or may not be the same workbook这些可能是也可能不是同一个工作簿

Your code, refactoed你的代码,重构

Private Sub bo_combobox_Change()
    Dim a As String
    Dim pt As PivotTable
    Dim ws As Worksheet
    Dim wb as Workbook

    Set wb = ActiveWorkbook 'or ThisWorkbook, or select a book by any means you choose
    If bo_combobox.Value <> vbNullString Then       
        For Each ws In wb.Worksheets
            For Each pt In ws.PivotTables
                ' remainder of your code
                '...
            Next pt
        Next ws
    End If   
End Sub

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM