0

Good day,

I'm trying to get the range to create a pivot table. The Column amounts can differ each month and the rows. My code is not working at the marked section (Bold) to set the Pivot table range and I believe the line after that won't either to create the Pivot cache. Is there a better way to do it or to fix this code, please?

Dim RowsCount As Long, ColCount As Long
Dim wsStores As Worksheet
Dim pCache As PivotCache
Dim pTable As PivotTable
Dim PvtRange As Range
Dim lastRows As Long

Set wsStores = Worksheets.Add
RowsCount = Worksheets("Active Instances").Cells(14, 1).End(xlDown).Row
ColCount = Worksheets("Active Instances").Cells(14, Columns.Count).End(xlToLeft).Column
**PvtRange = Worksheets("Active Instances").Range(RowsCount, ColCount)**
Set pCache = ActiveWorkbook.PivotCaches.Create(xlDatabase, PvtRange)
Set pTable = pCache.CreatePivotTable(wsStores.Range("A3"))
1
  • PvtRange is a Range object. You need to prefix it with the word "Set" like so: Set PvtRange = Worksheets("Active Instances").Range(RowsCount, ColCount). But even then, this code isn't going to work, as that just sets the range to a single cell, and you can't make a PivotTable out of a single cell. Commented Sep 9, 2017 at 20:14

1 Answer 1

0

Thanks for the reply @jeffreyweir I managed to fix it with the following code:

Dim wsStores As Worksheet
Dim pCache As PivotCache
Dim pTable As PivotTable
Dim lastRows As Long

Set wsStores = Worksheets.Add
Set pCache = ActiveWorkbook.PivotCaches.Create(xlDatabase, Sheets("Active Instances").Range("A14").CurrentRegion.Address(ReferenceStyle:=xlR1C1))
Set pTable = pCache.CreatePivotTable(wsStores.Range("A3"))

I didn't want to change from the pivot table to ListObject because the rest of the code (which was fine but not added into the question) was already set up without any problems. In the future, I will definitely try using the ListObject

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.