简体   繁体   English

根据单元格将数据字段添加到数据透视表

[英]Add Data field to Pivot based on cell

I am trying to create an interactive pivot table by allowing the user to select which data field to show (ie dollars earned, dollars spent).我试图通过允许用户选择要显示的数据字段(即赚取的美元、花费的美元)来创建一个交互式数据透视表。 I have the following code that works我有以下有效的代码

Sub AddMoreFields()

 With ActiveSheet.PivotTables("PivotTable1")
 .AddDataField ActiveSheet.PivotTables( _
 "PivotTable1").PivotFields("Dollars_spent")
 End With

End Sub

However, i want to change it to something like the following, so that a user can select which data to show但是,我想将其更改为以下内容,以便用户可以选择要显示的数据

Sub AddMoreFields()

 With ActiveSheet.PivotTables("PivotTable1")
 .AddDataField ActiveSheet.PivotTables( _
 "PivotTable1").PivotFields(Range("d21"))
 End With

End Sub

Range("D21") would actually be a drop down list in which a user could select between dollars earned and dollars spent. Range("D21") 实际上是一个下拉列表,用户可以在其中选择赚取的美元和花费的美元。 However, when i try use this i get an error stating that Rang("D21") is not a pivot field.但是,当我尝试使用它时,我收到一条错误消息,指出 Rang("D21") 不是枢轴字段。

Any suggestions?有什么建议?

Sub adddynamic()
Dim pt As PivotTable
Dim pf As PivotField
Dim f As String

f = Range("d21")
Set pt = ActiveSheet.PivotTables("PivotTable1")
Set pf = pt.PivotFields(f)
pt.AddDataField pf, "Sum of " & f, xlSum

End Sub

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM