i have 2 CSV files orders_by_user_backlog and orders_by_user_pivot. I want to create with VBA an .xlsx file called Orders by Users Report containing 2 sheets.
First sheet called backlog, i will just copy the data from orders_by_user_backlog.csv and paste it there.
Second sheet called pivot, i will copy the data from orders_by_user_pivot.csv and paste it there and refresh the pivot table in the same sheet with the new data.
I am using an .xlsx file as template called Orders By Users Template
Here is my code
Sub Orders_by_User_report()
Application.ScreenUpdating = False
Application.DisplayAlerts = False
'open the csv output from query orders by user backlog
Workbooks.Open FileName:="C:\Reports\orders_by_user_backlog.csv"
Cells.Select
Selection.Copy
Workbooks.Open FileName:= _
"C:\Reports\Report templates\Orders By Users Template.xlsx"
Sheets(1).Select
Cells.Select
ActiveSheet.Paste
'Bold and color top row, add autofilter, zoom 80% and autofit
Range("A1:H1").Select
Selection.Interior.Color = 255
Selection.Font.Bold = True
Selection.AutoFilter
ActiveWindow.Zoom = 80
Cells.Select
Cells.EntireColumn.AutoFit
'open the csv output from query orders by user pivot
Workbooks.Open FileName:="C:\Reports\orders_by_user_pivot.csv"
Cells.Select
Selection.Copy
Workbooks.Open FileName:= _
"C:\Reports\Report templates\Orders By Users Template.xlsx"
Sheets(2).Select
Cells.Select
ActiveSheet.Paste
'Bold and color top row, add autofilter, zoom 80% and autofit
Range("A1:D1").Select
Selection.Interior.Color = 255
Selection.Font.Bold = True
Selection.AutoFilter
ActiveWindow.Zoom = 80
Cells.Select
Cells.EntireColumn.AutoFit
'refresh pivot table
Sheets(2).Select
ActiveSheet.PivotTables("PivotTable1").PivotCache.Refresh
'save file as xlsx for the output
ActiveWorkbook.SaveAs FileName:= _
"C:\Reports\Orders by Users\Orders by Users Report " & ".xlsx" _
, FileFormat:=xlOpenXMLWorkbook, CreateBackup:=False
ActiveWindow.Close
ActiveWindow.Close
Application.DisplayAlerts = True
Application.ScreenUpdating = True
End Sub
I know where is my problem, it's in the 'ActiveSheet' but i didn't know how to fix it. Everytime i am using
ActiveSheet.Paste
or
ActiveSheet.PivotTables("PivotTable1").PivotCache.Refresh
it shows me error in the second ActiveSheet.Paste, when i comment this part and try only with one CSV file it Pastes fine but then it stops again in the ActiveSheet.PivotTables.
Can anyone please advice me what to change in my code ? Thank you very much.
ActiveSheet.PivotTables("PivotTable1").RefreshTable
– Shai RadoPivotCache
first, and then update yourPivotTable
. – Shai Rado