【问题标题】:How to create a pivot field per table header in VBA?如何在 VBA 中为每个表头创建一个数据透视字段?
【发布时间】:2022-01-21 04:56:16
【问题描述】:

对于我的数据透视表,我想从我的源表中为每个选定的标题(例如“A”、“B”、“C”等)创建一个数据字段。我没有为每个标题编写单独的代码,而是通过标题创建一个循环,因为我有超过 10 个标题。

我尝试的循环代码:

Dim h As Variant
Dim p As Long
Dim hdrs As Variant 'table headers of interest
hdrs = Array("A","B","C")

For Each h In hdrs
    With PSheet.PivotTables(PTName).PivotFields(hdrs)
    .Orientation = xlDataField
    .Function = xlAverage
    .NumberFormat = "0.00"
    .Position = p + 1
    End With
Next h

我的代码的变量:

  • PSheet:包含我的数据透视表的工作表(工作表变量)
  • PTName:数据透视表的名称(字符串变量)

但是这段代码没有任何反应

【问题讨论】:

    标签: excel vba for-loop pivot-table


    【解决方案1】:

    这行得通:

    Dim hdrs As Variant
    Dim i As Long
    hdrs = Array("A", "B", "C")
    
    For Each Item In hdrs
        PSheet.PivotTables(PTName).PivotFields (Item)
        With PSheet.PivotTables(PTName).PivotFields(Item)
        .Orientation = xlDataField
        .Function = xlAverage
        .NumberFormat = "0.00"
        .Position = i + 1
        End With
    Next Item
    

    【讨论】:

      猜你喜欢
      • 2019-11-30
      • 1970-01-01
      • 2021-12-06
      • 1970-01-01
      • 2011-06-22
      • 2018-03-29
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多