传递一个variables枢轴归档名称来sortingVBA

我正在使用数据透视表,并使用下面的代码:

Sub SortCTRDescending() ActiveSheet.PivotTables("PivotTable6").PivotFields("Industry").AutoSort _ xlDescending, "Total CTR", ActiveSheet.PivotTables("PivotTable6"). _ PivotColumnAxis.PivotLines(6), 1 End Sub 

有没有办法通过数据透视字段"Industry"作为一个variables取决于在数据透视表行中select什么? 即如果行业更改为“列表名称”,将variables设置为所选行标签(假定只有一行标签)? 然后这些传递给一个button,这将按照“点击率sorting”或“打开比率sorting”,其中列号保持不变。

编辑:添加了数据的屏幕截图。 行标签是行业,但这可以更改为任何其他领域,我怎样才能使第一行标签的主要sortingvariables。

Excel工作表

您可以遍历数据透视表的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