首页 > 解决方案 > 我创建数据透视的代码有效,但第一行字段无效

问题描述

我一直在尝试在 VBA 中创建一个数据透视表,即使在创建数据透视缓存和数据透视表之后我也部分成功了第一个 rowFeild 没有出现,但第二个 rowFeild 出现了,即使我已将它们编号为 .position=1 和.位置=2。请任何人帮助我,因为我是 VBA 编码的新手,需要帮助来解决这个问题。

在我将 xlRowField 指定为“自然帐户”的地方,我的数据中有该列以及“自然帐户描述”列,但代码仍然在行字段中完全跳过“自然帐户”并移至第二个不确定原因. 另外,如何将它放在经典的 Pivot 视图中,我的代码也不适用于此。

Dim PSheet As Worksheet
    Dim DSheet As Worksheet
    Dim PCache As PivotCache
    Dim PTable As PivotTable
    Dim PRange As Range
    Dim LastRow As Long
    Dim LastCol As Long

    'On Error Resume Next
    Worksheets("TempData").Activate
    Application.DisplayAlerts = False
    Worksheets("PivotTable").Delete
    Sheets.Add before:=ActiveSheet
    ActiveSheet.Name = "PivotTable"
    Application.DisplayAlerts = True
    Set PSheet = Worksheets("PivotTable")
    Set DSheet = Worksheets("TempData")

    'LastRow = DSheet.Cells(Rows.Count, 1).End(xlUp).Select
    'LastCol = DSheet.Cells(1, Columns.Count).End(xlToLeft).Column
    Set PRange = DSheet.Range("A1").CurrentRegion

    Set PCache = ActiveWorkbook.PivotCaches.Create(SourceType:=xlDatabase, SourceData:=PRange). _
    CreatePivotTable(tabledestination:=PSheet.Cells(2, 2), TableName:="SalesPivotTable")

    Set PTable = PCache.CreatePivotTable(tabledestination:=PSheet.Cells(2, 2), TableName:="SalesPivotTable")

    With ActiveSheet.PivotTables("SalesPivotTable").PivotFields("Natural Account")
        .Orientation = xlRowField
        .Position = 1
        '.InGridDropZones = True
        '.RowAxisLayout xlTabularRow
    End With

    With ActiveSheet.PivotTables("SalesPivotTable").PivotFields("Natural Account Description")
        .Orientation = xlRowField
        .Position = 2
    End With

    With ActiveSheet.PivotTables("SalesPivotTable").PivotFields("ME")
        .Orientation = xlColumnField
        .Position = 1
    End With

    With ActiveSheet.PivotTables("SalesPivotTable").PivotFields("Net Closing Balance")
        .Orientation = xlDataField
        .Position = 2
        .Function = xlSum
    End With

    ActiveSheet.PivotTables("SalesPivotTable").RowAxisLayout xlTabularRow

    'With ActiveSheet.PivotTables("SalesPivotTable")
        '.InGridDropZones = True
        '.RowAxisLayout xlTabularRow
    'End With

标签: vbaexcelpivot-table

解决方案


推荐阅读