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.