簡體   English   中英

循環以基於另一個工作表中的值過濾數據透視表

[英]Loop to filter Pivot Table based on values in another Sheet

我的目標是使用另一個工作表中的范圍來過濾數據透視表。

我的工作重點在工作表(“帳齡報告”)中。

我要用來過濾的參考數據在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

一些有用的准則:

原始數據:

在此處輸入圖片說明

選擇數據並在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

對於按值過濾,我的首選方法是向數據本身添加更多列,通過公式設置值,然后將這些列添加到數據透視表中

例如,將Scope布爾值列添加到數據透視過濾器中,僅對true進行過濾

添加30/60/90時效列,將其添加到數據透視行中以按年齡分組

等等

這樣,您就可以避免將兩個鮮為人知的專業知識vba和針對樞軸的vba相結合的復雜性

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM