传递变量数据透视字段名称进行排序 VBA
Pass A Variable Pivot Filed Name To Sort VBA
我正在使用数据透视表 table,并使用以下代码:
Sub SortCTRDescending()
ActiveSheet.PivotTables("PivotTable6").PivotFields("Industry").AutoSort _
xlDescending, "Total CTR", ActiveSheet.PivotTables("PivotTable6"). _
PivotColumnAxis.PivotLines(6), 1
End Sub
有没有办法根据在数据透视表 table 行中选择的内容将数据透视表字段 "Industry"
作为变量传递?即,如果 Industry 更改为“List Name”,是否将变量设置为所选的任何行标签(假设只有 1 个行标签)?然后将这些传递给一个按钮,该按钮将“按点击率排序”或“按打开率排序”,其中列号保持不变。
编辑:添加了数据的屏幕截图。行标签是行业,但这可以更改为任何其他字段,如何使第一行标签成为主要排序变量。
您可以循环遍历数据透视表的 RowFields
来查找当前字段的名称。代码检查以确保 table 当前只有 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
我正在使用数据透视表 table,并使用以下代码:
Sub SortCTRDescending()
ActiveSheet.PivotTables("PivotTable6").PivotFields("Industry").AutoSort _
xlDescending, "Total CTR", ActiveSheet.PivotTables("PivotTable6"). _
PivotColumnAxis.PivotLines(6), 1
End Sub
有没有办法根据在数据透视表 table 行中选择的内容将数据透视表字段 "Industry"
作为变量传递?即,如果 Industry 更改为“List Name”,是否将变量设置为所选的任何行标签(假设只有 1 个行标签)?然后将这些传递给一个按钮,该按钮将“按点击率排序”或“按打开率排序”,其中列号保持不变。
编辑:添加了数据的屏幕截图。行标签是行业,但这可以更改为任何其他字段,如何使第一行标签成为主要排序变量。
您可以循环遍历数据透视表的 RowFields
来查找当前字段的名称。代码检查以确保 table 当前只有 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