【问题标题】:Loop to filter Pivot Table based on values in another Sheet循环以根据另一个工作表中的值过滤数据透视表
【发布时间】:2019-05-23 01:31:59
【问题描述】:

我的目标是使用另一个工作表中的范围过滤数据透视表。

我的支点在 Worksheets("Aging Report") 中。

我要过滤的参考数据位于 A2 列及 Worksheets("Instructions") 中。

以下代码适用于没有数据透视表的表。

我需要从 A2 中获取值,然后过滤(“客户 ID”)并在 Excel 中导出并保存等等,然后使用 A3、A4、A5 中的值。

Sub Pivotfilter()

Dim varItemsToReplace As Variant
Dim varItem As Variant
Dim wksSource As Worksheet
Dim wksDest As Worksheet
Dim rngSource As Range
Dim rngSource2 As Range
Dim rngCell As Range

Set wksSource = Worksheets("Instructions")
Set wksDest = Worksheets("Aging Report")

With wksSource
    Set rngSource = .Range("A2:A" & .Cells(.Rows.Count, "A").End(xlUp).Row)
End With

For Each rngCell In rngSource
    With wksDest
        ActiveSheet.PivotTables("PivotTable40").PivotFields ("Client ID")
        .PivotFields(rngCell.Value).Visible = True
        Dim wb As Workbook
        Set wb = Workbooks.Add
        Windows("XXXXXXX").Activate
        Sheets("Aging Report").Select
        Sheets("Aging Report").Copy Before:=wb.Sheets(1)
        wb.SaveAs "C:\Users\XXX\Desktop\SOA\" & .Range("B3").Value & " - " & .Range("B4").Value & ".xlsx"
        wb.Close
        Windows("XXXXXXX.xlsm").Activate
    End With
Next rngCell

End Sub

【问题讨论】:

    标签: excel vba loops pivot-table


    【解决方案1】:

    对于按值过滤,我首选的方法是向数据本身添加更多列,通过公式设置值,然后将这些列添加到数据透视表

    例如,列 Scope boolean 添加到枢轴过滤器,仅过滤 true

    添加 30/60/90 老化列,将此添加到数据透视行以按年龄分组

    等等

    这可以让您避免将两个鲜为人知的专业领域 vba 和 vba 专门用于枢轴的复杂性结合起来

    【讨论】:

      【解决方案2】:

      一些有用的指南:

      原始数据:

      选择数据并在 Shhet 5 中创建一个名为“pvtTest”的数据透视表

      试试:

      Option Explicit
      
      Sub test()
      
          Dim pvt As PivotTable
          Dim Pf As PivotField
          Dim strFilter As String
      
          'Assign to variable "pvt" the pivot table to work with it
          Set pvt = Worksheets("Sheet5").PivotTables("pvtTest")
      
          'Assigh to "strFilter" the string to filter
          strFilter = "A"
      
          'Use column "Shop" as a filter of pivot table
          pvt.PivotFields("Shop").Orientation = xlPageField
      
          'Assign by which column the pivot table will be filtered
          Set Pf = Worksheets("Sheet5").PivotTables("pvtTest").PivotFields("Shop")
      
          'Clear filter previous choices
          Pf.ClearAllFilters
      
          'Select to filter the pivot table based on the value of "strFilter"
          Pf.CurrentPage = strFilter
      
      End Sub
      

      【讨论】:

        猜你喜欢
        • 2017-04-29
        • 1970-01-01
        • 2014-07-27
        • 2020-10-10
        • 2014-05-25
        • 1970-01-01
        • 1970-01-01
        • 2017-11-22
        • 2018-08-12
        相关资源
        最近更新 更多