Manually I would click the check box to “Add this data to the Data Model”. I am new to VBA and am writing multiple sections to make manipulating these reports daily easier. I have copied and written code from multiple web pages and using the record macros while learning so it may be a bit of a mix!
I have been able to get everything to work except adding the connection so I can summarize by distinct count.
My main concern with this is that my file name and range will change daily as well.
I would appreciate any assistance!
I have been able to get everything to work except adding the connection so I can summarize by distinct count.
My main concern with this is that my file name and range will change daily as well.
I would appreciate any assistance!
VBA Code:
Sub InsertPivotTable()
'
'
'
'Declare Variables
Dim PSheet As Worksheet
Dim DSheet As Worksheet
Dim PCache As PivotCache
Dim PTable As PivotTable
Dim PRange As Range
Dim LastRow As Long
Dim LastCol As Long
'Insert a New Blank Worksheet
On Error Resume Next
Application.DisplayAlerts = False
Worksheets("Summary").Delete
Sheets.Add Before:=ActiveSheet
ActiveSheet.Name = "Summary"
Application.DisplayAlerts = True
Set PSheet = Worksheets("Summary")
Set DSheet = Worksheets("Detail")
'Define Data Range
LastRow = DSheet.Cells(Rows.Count, 1).End(xlUp).Row
LastCol = DSheet.Cells(1, Columns.Count).End(xlToLeft).Column
Set PRange = DSheet.Cells(1, 1).Resize(LastRow, LastCol)
'Add WB Connection
MainWB.Connections.Add2 ("WorksheetConnection_ ActiveWorkbook, "", _
"WORKSHEET;C:\Users\217216X721431\Documents\Test Reports\[Compliance Completion report as of 10.25.xlsm]Detail _
, "Detail!$A$1:$X$11446", 7, True, False
'Define Pivot Cache
Set PCache = ActiveWorkbook.PivotCaches.Create _
(SourceType:=xlDatabase, SourceData:=PRange). _
CreatePivotTable(TableDestination:=PSheet.Cells(2, 2), _
TableName:="Pivot Table")
'Insert Blank Pivot Table
Set PTable = PCache.CreatePivotTable _
(TableDestination:=PSheet.Cells(1, 1), TableName:="Pivot Table")
'Insert Row Fields
With ActiveSheet.PivotTables("Pivot Table").PivotFields("HRBP")
.Orientation = xlRowField
.Position = 1
End With
With ActiveSheet.PivotTables("Pivot Table").PivotFields("1st level structure Description")
.Orientation = xlRowField
.Position = 2
End With
'Insert Column Fields
With ActiveSheet.PivotTables("Pivot Table").PivotFields("All CUR Complete")
.Orientation = xlColumnField
.Position = 1
End With
'Insert Data Field
With ActiveSheet.PivotTables("Pivot Table").PivotFields("User")
.Orientation = xlDataField
.Function = xlSum
.NumberFormat = "#,##0"
.Name = "Revenue "
End With
Sheets("Summary").PivotTables("Pivot Table").PivotFields("[Measures].[Sum of User]"). _
Function = xlDistinctCount
'Format Pivot Table
ActiveSheet.PivotTables("Pivot Table").ShowTableStyleRowStripes = True
ActiveSheet.PivotTables("Pivot Table").TableStyle2 = "PivotStyleMedium9"
End Sub