是否可以将数据透视表切片器从最大到最小排序?

时间:2018-01-10 06:06:38

标签: excel excel-vba pivot-table vba

我创建了一个带有增益和损失的新表。我的目标是获得从最大到最小的表格排序。损失从最小到最大排序。我尝试了一些vba,但无法对值进行排序。

Sub Macro1() 

Dim wb As Workbook 
Dim ws As Worksheet 
Dim targetTable As ListObject 
Set wb = ThisWorkbook 
Set ws = wb.Worksheets("Project Dash") 

If Worksheets("Project Dash").SlicerCaches("Slicer_Gains__Losses") .SlicerItems("Gai‌​ns").Selected = True Then 

    ActiveSheet.PivotTables("ProjectGain20").PivotFields("Projec‌​t").AutoSort _ xlDescending, "Sum of Work Variance", ActiveSheet.PivotTables("ProjectGain20"). _ PivotColumnAxis.PivotLines(1), 1 

End If 

End Sub

1 个答案:

答案 0 :(得分:0)

以下是使用“选项”按钮对支持表进行排序的示例。切片器旨在过滤您的数据,而不是对其进行排序。当您添加表单控件单选按钮/选项按钮时,您需要编辑文本,如我的图像所示,然后右键单击每个按钮并将每个按钮与宏CheckOptions相关联。这里排序的字段是[Value1],您可以根据需要进行更改。您的数据需要设置为表格,如图所示。

我使用@L42的建议来检查哪个选项按钮称为宏。

排序顺序枚举为here

Table set up and form control option buttons

进入标准模块的代码:

Option Explicit

Public Sub CheckOptions()                        

    Dim wb As Workbook
    Dim ws As Worksheet
    Dim targetTable As ListObject

    Set wb = ThisWorkbook
    Set ws = wb.Worksheets("Sheet1") 'Change as appropriate
    Set targetTable = ws.ListObjects("Table1")

    Select Case Application.Caller

    Case "Option Button 1"

        SortTable targetTable, 2

    Case "Option Button 2"

        SortTable targetTable, 1

    End Select
End Sub

Private Sub SortTable(ByRef targetTable As ListObject, ByVal myOrder As Byte) 'https://msdn.microsoft.com/en-us/vba/excel-vba/articles/xlsortorder-enumeration-excel

    With targetTable.Sort

        .SortFields.Clear

        .SortFields.Add _
        Key:=Range("Table1[[#All],[Value1]]"), SortOn:=xlSortOnValues, order:= _
                   myOrder, DataOption:=xlSortNormal

        .Header = xlYes
        .MatchCase = False
        .Orientation = xlTopToBottom
        .SortMethod = xlPinYin
        .Apply

    End With

End Sub