How to create a dynamic table with multiple line fields using VBA?

Asked

Viewed 282 times

1

I want to create a dynamic table with several line fields. But, these line fields need to be changed according to the data entered in the Excel spreadsheet.

I tried to define the variables and use "With" and "for" commands, 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 'digitar os campos na coluna "F".
            For i = 1 To RLast
                Set X = Wsheet.Range("F" & i)
                With .PivotFields(X)             'o erro ocorre nesse comando
                    .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

The "X" variable stores the correct field name, but the debug command with error 1004: cannot get the Pivotfields property of the Pivottable class.

1 answer

1

I figured out how to solve: Variable X must be set to String

Dim X as String

X = Wsheet.Range("F" & i)

Also, there was an error in the command for for i should start with 1

Browser other questions tagged

You are not signed in. Login or sign up in order to post.