前言:
我正在尝试构建一个不依赖于绝对引用的宏。
问题:
我的宏的一部分需要活动数据透视表的“值”象限中的字段名称。
字段名称将更改,因此我无法将其硬编码到我的宏中。(上图中是“AMT”,但在另一个数据透视表中可能是“Amount”,这就是为什么我需要它是动态的。)
如果我在值象限中有一个字段,如何将其名称作为字符串获取?如果我可以将它的名称作为字符串获取,我可以将其输入到我拥有的宏中。
说到这里,我的代码仅供参考:
Sub PivotNumberFormat()
'PivotNumberFormat Macro
'Formats the "Values" data field in the currently active pivot to: number format, 2 decimals, and commas
'=============================================
'Define variables
Dim PT As PivotTable
'=============================================
'Continue if pivot table not selected
On Error GoTo EndSub
'=============================================
'Set pivot table as variable "PT"
Set PT = ActiveCell.PivotTable
'=============================================
'If pivot table selected, change number format
If Not PT Is Nothing Then
'Change the format of the pivot table amt field
With PT.PivotFields("Sum of AMT") '<-------------This is the line where I need a dynamic reference.
.NumberFormat = "#,##0.00_);(#,##0.00)"
End With
'Notify user that format was changed
MsgBox "Format Changed"
'Stop macro
Exit Sub
End If
'=============================================
'If error, notify user and stop macro
EndSub:
MsgBox "Format NOT Changed"
End Sub
您可以看到大约在中途我放了一个注释,显示需要动态引用名称的 PivotFields 对象。而不是读取“(AMT 的总和)”的代码,我希望它读取“([FieldName] 的总和)”,其中 [FieldName] 是随数据透视表更改的动态字段名称字符串。
在我使用这个宏的绝大多数时间里,值象限中只有一个字段。如果很容易使宏扩展到值象限中的多个字段,那是一个好处,但绝对不是必需的或不需要的。
我知道 PivotTable vba 很复杂,因此我感谢您带来的任何宝贵见解!
谢谢,洛根