我正在使用数据透视表,并使用以下代码:
Sub SortCTRDescending()
ActiveSheet.PivotTables("PivotTable6").PivotFields("Industry").AutoSort _
xlDescending, "Total CTR", ActiveSheet.PivotTables("PivotTable6"). _
PivotColumnAxis.PivotLines(6), 1
End Sub
是否有办法将数据透视字段"Industry"
作为变量传递,具体取决于数据透视表行中选择的内容?即如果Industry更改为" List Name",请将变量设置为所选的任何行标签(仅假设1行标签)?然后将这些传递给一个按钮,按钮按“CTR”排序。或者"按开放率排序"列数保持不变。
编辑:添加了数据的屏幕截图。行标签是行业,但这可以更改为任何其他字段,如何将第一行标签作为主要排序变量。
答案 0 :(得分:2)
您可以遍历数据透视表的RowFields
以查找当前字段的名称。代码检查以确保表当前只有1 RowField
。对特定对象名称进行调整。
Sub SortCTRDescending()
Dim ws As Worksheet
Dim pt As PivotTable
Dim pf As PivotField, pField As PivotField
Dim sField As String
Set ws = Worksheets("Sheet1") 'change as needed
Set pt = ws.PivotTables("PivotTable6")
If pt.RowFields.Count = 1 Then
'note that even though there is only one field, the loop is needed to get the name
For Each pField In pt.RowFields
sField = pField.Name
Next
Else
MsgBox "Whoa! More Than 1 Row Field!"
Exit Sub
End If
Set pf = pt.PivotFields(sField)
pf.AutoSort xlDescending, "Total CTR", pt.PivotColumnAxis.PivotLines(6), 1
End Sub