传递变量透视字段名以对VBA进行排序
我正在使用数据透视表,并使用以下代码:传递变量透视字段名以对VBA进行排序,vba,excel,pivot,Vba,Excel,Pivot,我正在使用数据透视表,并使用以下代码: Sub SortCTRDescending() ActiveSheet.PivotTables("PivotTable6").PivotFields("Industry").AutoSort _ xlDescending, "Total CTR", ActiveSheet.PivotTables("PivotTable6"). _ Piv
Sub SortCTRDescending()
ActiveSheet.PivotTables("PivotTable6").PivotFields("Industry").AutoSort _
xlDescending, "Total CTR", ActiveSheet.PivotTables("PivotTable6"). _
PivotColumnAxis.PivotLines(6), 1
End Sub
是否有方法根据数据透视表行中选择的内容将数据透视字段作为变量传递?i、 e.如果行业更改为“列表名称”,是否将变量设置为所选的任何行标签(假设只有一行标签)?然后,这些数据被传递到一个按钮,该按钮将“按CTR排序”或“按开放率排序”,其中列数保持不变
编辑:添加了数据的屏幕截图。行标签是行业,但这可以更改为任何其他字段,如何使第一行标签成为主要排序变量
您可以在数据透视表的
行字段中循环查找当前字段的名称。代码检查以确保表当前只有1个行字段
。对特定的对象名称进行调整
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
您可以在数据透视表的行字段中循环查找当前字段的名称。代码检查以确保表当前只有1个行字段
。对特定的对象名称进行调整
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
这假设名称出现在某个位置,但实际情况并非如此。那么有没有办法解析出当前活动的Pivot字段,然后将该值传递到一个范围内?@GregdeLima你能用截图解释更新我们的问题吗?我不知道你所说的当前活动轴字段是什么意思。添加了屏幕截图。好的-我现在明白了。请给我一点时间,我会更新我的答案。我必须将.Count
添加到RowFields=1
。这假设名称出现在某个位置,但它没有。那么有没有办法解析出当前活动的Pivot字段,然后将该值传递到一个范围内?@GregdeLima你能用截图解释更新我们的问题吗?我不知道你所说的当前活动轴字段是什么意思。添加了屏幕截图。好的-我现在明白了。请给我一点时间,我会更新我的回答。我必须将.Count
添加到行字段=1
。