繁体   English   中英

如何使用VBA创建包含多个行字段的数据透视表?

[英]How to creat a pivot-table with multiple line fields using VBA?

我想创建一个包含多个行字段的数据透视表。 虽然,这些行字段需要相应地更改为excel表中键入的数据。

我已经尝试设置变量并使用“with”和“for”命令,例如在下面的代码中。

    Option Explicit 
Private Sub PivotTable()

        Dim Wsheet      As Worksheet, Wsheet2   As Worksheet
        Dim File        As Workbook
        Dim PvtCache    As PivotCache
        Dim Pvtbl       As PivotTable
        Dim RLast       As Double
        Dim i           As Variant, X            As Variant

        Set File = ThisWorkbook
        Set Wsheet = Sheets("Data")
        'Create sheet for pivot table 
        Set Wsheet2 = Sheets.Add(After:=Wsheet)
        Wsheet2.Name = "PivotTable"     

        Set PvtCache = File.PivotCaches.Create(SourceType:=xlDatWsheetse, SourceData:=Wsheet.Range("A1:D45"))
        Set Pvtbl = Wsheet2.PivotTables.Add(PivotCache:=PvtCache, TableDestination:=Wsheet2.Range("A3"), TableName:="Manual_Bordo")

            With Pvtbl
            'setting rows fields
            Set Wsheet = Sheets("Data")
            RLast = Wsheet.Cells(Rows.Count, "F").End(xlUp).Row 'Type the row fields in column "F".
            For i = 1 To RLast
                Set X = Wsheet.Range("F" & i)
                With .PivotFields(X)                            'Here i get  the error 1004
                    .Orientation = xlRowField
                    .Position = i
                End With

            Next
            'setting pivot Data
                With .PivotFields("Size")
                    .Orientation = xlDataField
                    .Position = i
                    .Function = xlSum
                    .NumberFormat = "#.##0,0"
                    .Name = "Size"
                End With
            Next            
        End With
    Application.DisplayAlerts = True
End Sub

但反过来工作我得到错误1004:无法获得数据透视表类的pivotfields属性(抱歉,如果它没有意义,但我不得不翻译对话框)。

您正在使用一个只需要字符串的对象。 (我也在重命名X以使其更清晰):

Dim rowLabel as String
...
rowLabel = Wsheet.Range("F" & i)
With .PivotFields(rowLabel)
    ...

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM