0

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). Within 2nd For loop, I am trying to change the pivot filter value based on a combobox selection.

Below is the code, but it does not loop through the 2nd for loop.


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
4

1 回答 1

1

你的(被问到的)问题是

For Each pt In ThisWorkbook.PivotTables

Workbook.PivotTables系列不是看起来的那样:

文档

Workbook 对象的 PivotTables 属性不会返回工作簿中的所有 PivotTable 对象;相反,它只返回与解耦数据透视图关联的那些。但是,Worksheet 对象的 PivotTables 方法会返回工作表上的所有 PivotTable 对象,无论它们是否与解耦的 PivotCharts 相关联。

也就是说,还有其他几个问题

  1. 你有For Each ws In ActiveWorkbook.Worksheets然后不要使用ws
  2. 您同时引用ActiveWorkbookThisWorkbook。这些可能是也可能不是同一个工作簿

你的代码,重构

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
于 2021-07-07T22:28:21.557 回答