Good mrng!
I am trying to create pivot table using vba and i am very new to pivot using vba and i tried to research in google as much as possible to get this corrected but didnt find much info which can help me to fix it, would be of great help if anyone can help me with this.
Range - always starts from A10, columns will be fixed until H but number of rows are not fixed hence i tried to define the range and use it in the code but its throwing me below error message, please check and correct me
Issues faced-Not able to define Rng as Range and not able to use this range in the pivot table.
Rng as Range
Run time error '91': Object variable or with black variance not set
Pivot cache
Run Time error '438': Object doesn't support this property or method
Data
ACT AN Currency CB LC Type CB FC Type SI
1001 c USD 2,031 Dr 2,031 Dr 0005
1002 a BHD 1,194 Dr 1,194 Dr 0105
1003 P EUR 326 Dr 326 Dr 0110
1004 AR GBP 60,467 Dr 60,467 Dr 0125
1005 AP DHS (73,080) Cr (73,080) Cr 0190
Sub Pivot()
Dim ws As Worksheet
Dim pc As PivotCache
Dim pt As PivotTable
'Dim Rng As Range
'Defining Range
Rng = Range("A10").Select
Rng = Range(Selection, Selection.End(xlToRight)).Select
Rng = Range(Selection, Selection.End(xlDown)).Select
'Adding new worksheet
Set ws = Worksheets.Add
'Creating Pivot cache
Set pc = ActiveWorkbook.PivotCaches.Create(xlDatabase, "Working!Rng").Select
'Creating Pivot table
Set pt = pc.CreatePivotTable(ws.Range("B3"))
'Setting Fields
With pt
'set row field
With .PivotFields("SI")
.Orientation = xlRowField
.Position = 1
End With
'set column field
With .PivotFields("Currency")
.Orientation = xlColumnField
.Position = 1
End With
End With
End Sub
Thanks for your help!
Regards Suresh7860
.Select
at the end like so:Set Rng = Range("A10")
. Also, why are you re-assigning therng
within three consecutive rows? Finally, it doesn't make sense to me that you first "create" a new PivotCache and then create a pivot table (with no relationship to the cache). There doesn't even seem to be a data source for your pivot table. Have you tried recording a macro and read / understand it? – Ralph