有关添加数据透视表字段的查询

时间:2019-04-07 14:22:58

标签: excel vba

我正在尝试使报表创建过程自动化,而我陷入其中。该代码应创建一个数据透视表,并以行的形式显示用户名,同时以相应的值显示用户名的计数。我创建了数据透视表,并通过以下代码在行中设置了用户名。

ActiveWorkbook.PivotCaches.Create(xlDatabase, `Sheets("Days").Range("A1:B10000")).CreatePivotTable `Sheets("Days").Range("E1"), "DayData"
ActiveWorkbook.ShowPivotTableFieldList = True

With PivotFields
   With ActiveSheet.PivotTables(1).PivotFields("User Name")
        .Orientation = xlRowField
        .Position = 1
    End With

我需要知道如何显示除用户名之外的用户名计数。可以通过以下方式手动表示:将用户名拖到行下,然后再次将用户名拖到值下以获取用户名计数。

我还可以询问如何将过滤器应用于数据透视表

1 个答案:

答案 0 :(得分:1)

以下是一些示例:

Private Sub DayDataPivotTable()
    Dim wb As Workbook
    Dim ws As Worksheet
    Dim pCache As PivotCache
    Dim pTable As PivotTable

    Set wb = ActiveWorkbook
    Set ws = ActiveSheet

    Set pCache = wb.PivotCaches.Create(xlDatabase, ws.Range("A1:B10000"))
    Set pTable = pCache.CreatePivotTable(ws.Range("E1"), "DayData")
    wb.ShowPivotTableFieldList = True

    With pTable
        With .PivotFields("User Name")
            ' use it as row field:
            .Orientation = xlRowField
            .Position = 1

            ' use it additionally as data field:
            .Orientation = xlDataField
            .Position = 1
            .Caption = "Count of Usernames"
            .Function = xlCount
        End With

        With .RowFields(1)
            ' filter the row field:
            .ClearAllFilters
            .EnableMultiplePageItems = True
            .PivotItems("John Doe").Visible = False
            .PivotItems("(blank)").Visible = False
        End With

        With .PivotFields(2)
            ' use the second column as separate filter:
            .Orientation = xlPageField
            .Position = 1
        End With

    End With
End Sub