为什么我的代码没有生成正确的数据透视表?

时间:2019-06-25 23:28:20

标签: vba pivot-table

我已经编写了一个VBA程序来创建数据透视表并填充数据。它可以按预期工作,但是它具有许多硬编码部分,因此我正在对其进行重写以使其更加通用,从而可以重用该子例程。但是,重新编写的代码不会产生与原始代码相同的结果,而且我也不知道为什么。

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

因为有很多行代码,所以我只展示有问题的部分。 (请告诉我是否需要更多代码来回答我的问题)

'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

1 个答案:

答案 0 :(得分:3)

有“ s”(两个)

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

缺少两个“ s”

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