New to VBA and I've been struggling to find the right data source for my Pivot table in Excel. The data source should be coming from column "B" in sheet "Monthly". Any tips on how to change data source or a different method for it?
This is what i have so far:
Dim PSheet As Worksheet
Dim DSheet As Worksheet
Dim PvtCache As PivotCache
Dim PvtTable As PivotTable
Dim DR As Range
Dim LR As Long
Dim LC As Long
Dim sht5 As Variant
On Error GoTo errhandler
With Application
.DisplayAlerts = False
.ScreenUpdating = False
End With
For Each sht5 In ActiveWorkbook.Worksheets
If sht5.Name = "Pivot" Then
sht5.Delete
End If
Next sht5
On Error GoTo 0
Worksheets.Add.Name = "Pivot"
Set DSheet = Worksheets("Monthly")
Set PSheet = Worksheets("Pivot")
LR = DSheet.Cells(Rows.Count, 1).End(xlUp).Row
LC = DSheet.Cells(1, Columns.Count).End(xlToLeft).Column
Set DR = DSheet.Cells(1, 1).Resize(LR, LC) 'this line is what i can't figure out
Set PvtCache = ActiveWorkbook.PivotCaches.Create(SourceType:=xlDatabase, SourceData:=DR)
Set PvtTable = PvtCache.CreatePivotTable(TableDestination:=PSheet.Cells(1, 1), TableName:="Monthly")
With ActiveSheet.PivotTables("Monthly").PivotFields("Chutes")
.Orientation = xlRowField
.Position = 1
End With
With ActiveSheet.PivotTables("Monthly").PivotFields("Chutes")
.Orientation = xlDataField
.Position = 1
.Function = xlCount
End With
Thanks!
LR, try usingSet DR = DSheet.Range( DSheet.Range("B1"), DSheet.Cells(LR, LC) )