【问题标题】:Why is my code not producing a correct pivot table?为什么我的代码没有生成正确的数据透视表?
【发布时间】:2019-06-25 23:28:20
【问题描述】:

我编写了一个 VBA 程序来创建数据透视表并填充数据。它按预期工作,但它有很多硬编码的部分,所以我正在重写它以使其更通用,以便我可以重用子例程。但是重写后的代码和原来的结果不一样,我也不知道为什么。

我传递了正确的参数,它没有返回任何错误。它实际上创建了一个空数据透视表,但它不填充数据(RowFields)。

由于代码行多,我只展示有问题的部分。 (如果您需要更多代码来回答我的问题,请告诉我)

'This is the portion adding RowField, and this works, but it is hard coded. Too much of repetitive code!
With ActiveSheet.PivotTables("MyPivot").PivotFields("ColumnName1")
    .Orientation = xlRowField
    .Position = 1
End With
With ActiveSheet.PivotTables("MyPivot").PivotFields("ColumnName2")
    .Orientation = xlRowField
    .Position = 2
End With
With ActiveSheet.PivotTables("MyPivot").PivotFields("ColumnName3")
    .Orientation = xlRowField
    .Position = 3
End With

'And this is the rewritten code with loop, but it does not add any data to the pivot table.
'Argument1: ArrayRowField - a string array containing "Column1", "Column2", and "Column3"
'Argument2: PivotTableName - a string containing "MyPivot"
Dim counter As Integer
For counter = 0 To UBound(ArrayRowField)
    With ActiveSheet.PivotTable(PivotTableName).PivotField(ArrayRowField(counter))
        .Orientation = xlRowField
        .Position = (counter + 1)
    End With
Next counter

对我来说,这两个看起来应该表现得一样。但只有顶部的工作,将行字段添加到方向,但底部没有。 谁能告诉我我做错了什么?

编辑:我只是尝试将with 语句置于循环之外,但没有任何区别。

'This did nothing to fix my problem
Dim counter As Integer
With ActiveSheet.PivotTable(PivotTableName).PivotField(ArrayRowField(counter))
    For counter = 0 To UBound(ArrayRowField)
        .Orientation = xlRowField
        .Position = (counter + 1)
    Next counter
End With

【问题讨论】:

    标签: vba pivot-table


    【解决方案1】:

    有“s”(两个)

    With ActiveSheet.PivotTables("MyPivot").PivotFields("ColumnName2")
                               ^                      ^
    

    缺少两个“s”

    With ActiveSheet.PivotTable(PivotTableName).PivotField(ArrayRowField(counter))
    

    【讨论】:

    • 我现在觉得自己好笨,好尴尬。谢谢,这就是问题的原因。我只是在两者中添加了“s”,它解决了问题。哇。
    • 我们都盯着这样的东西看了好几个小时,却没有看到。
    猜你喜欢
    • 1970-01-01
    • 2019-07-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-03-12
    • 1970-01-01
    • 1970-01-01
    • 2022-01-23
    相关资源
    最近更新 更多