vba - 在数据透视 + VBA + 动态解决方案中运行所有可能的页面过滤器组合

标签 vba dynamic excel combinations

我正在尝试创建一个动态的宏,并通过所有可能的页面过滤器组合运行并生成报告。

现在,我只有两个过滤器:AccountManager 和 CostCenter,下面的宏会遍历 AccountManager 的所有值及其对应的 CostCenter 值并准备报告。

Sub Run_All_Reports()
    Dim PT As PivotTable
    Dim PF As PivotField
    Dim PI As PivotItem, PI2 As PivotItem

    Sheets("Pivot").Activate
    Set PT = ActiveSheet.PivotTables("Budget")

    For Each PI In PT.pageFields(1).PivotItems
        PT.pageFields(1).CurrentPage = PI.Name
        For Each PI2 In PT.pageFields(2).PivotItems
            PT.pageFields(2).CurrentPage = PI2.Name
            Call Run_Report
        Next
    Next
End Sub

我不知道如何将此功能扩展为动态的,即它读取存在多少页面过滤器,然后为每个可能的组合准备报告。

可以说,我介绍了另一个过滤器 - 区域。然后它应该为所有可能的组合生成报告。下面的一个例子:
John, Marketing, London
John, Marketing, NewYork
John, Sales, London
Sam, Sales, London
Sam, Sales, NewYork

不确定我是否足够清楚。我试图四处寻找,但找不到解决方案。我被问到 2 页过滤器的这个问题,我已经实现了上述解决方案,但从昨天开始我就头疼,因为我希望它在我的脑海中是动态的。

最佳答案

使用递归过程,如下所示

例如

Sub RunForALlItems(PT as pivotTable, count as integer)
numFields= PT.pageFields.count
for each PI in PT.pageFields(num).PivotItems
   PT.pageFields(num).CurrentPage = PI.Name
   if (num=numFields) then
      call run_Report
   elseif (num<numFields) then
      call RunForAllItems(PT, count+1)
   end if
next
end sub

然后用
RunForAllItems(PT, 1)

我没测试过 ,但它应该 - 稍作调整 - 工作

关于vba - 在数据透视 + VBA + 动态解决方案中运行所有可能的页面过滤器组合,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16375332/

相关文章:

database - 如何通过表单向Ms Access中的表添加新记录?

python - sys.stderr 中何时不存在属性 `isatty()`?

jquery - 垂直居中内容除非更大

php - .xlsx 文件可以简化到什么程度

excel - 宏到自动填充

excel - 自动填充动态数据范围内的增量数

excel - 立方体场?在数据透视表上设置过滤器值

c# - Excel.Worksheet.Cells[row,col] = "=Formula"与 Range.set_Value(Missing.Value, arrayFormulas)

C++ 内存分配。矩阵

java - POI - ZIP 条目大小太大