我的目标是使用另一个工作表中的范围来过滤数据透视表。
我的关键点在Worksheets(“帐龄报告”)中。
我要用来过滤的参考数据在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
答案 0 :(得分:0)
一些有用的准则:
原始数据:
选择数据并在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
答案 1 :(得分:0)
对于按值过滤,我的首选方法是向数据本身添加更多列,通过公式设置值,然后将这些列添加到数据透视表中
例如,列Scope布尔添加到数据透视过滤器中,仅在true时过滤
添加30/60/90老化列,将其添加到数据透视行中以按年龄分组
等
这使您避免了将两个鲜为人知的专业知识vba和针对枢轴的vba相结合的复杂性