简体   繁体   中英

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

I want to create a pivot table with multiple line fields. Although, these line fields need to be changed accordingly to data in typed in excel sheet.

I have tried setting the variables and using "with" and "for" commands, such as in the following code.

    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

But instead working I get the error 1004: cannot get the pivotfields property of the pivot table class (Sorry if it doesn't make sense, but I had to translate the dialog box).

You're using an object where you just need a string. (I'm also renaming X to make it more clear):

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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