【发布时间】: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