There are some xlsx files in "c:", exported from Microsoft Access table. There are about 4 files with equal number and names of columns but different data.
When the code starts running, it makes the first xlsx pivot correctly with no problems, but the second iteration causes errors here:
ActiveWorkbook.PivotCaches.Create(SourceType:=xlDatabase, SourceData:= _
fileName, Version:=6).CreatePivotTable TableDestination:= _
"Sheet1!R3C1", TableName:="PivotTable1", DefaultVersion:=6
Error: Run- time error '91' : Object Variable or with block variable not set
I've already tried to use "myWorkbook" before Sheets
, ActiveWorkbook
etc., but it didn't work or I didn't do it properly.
All Excel files should have pivot tables.
Sub test()
Dim strF As String, strP As String
Dim wb As Workbook
Dim ws As Worksheet
'Edit this declaration to your folder name
strP = "c:\" 'change for the path of your folder
strF = Dir(strP & "\*.xls*") 'Change as required
Do While strF <> vbNullString
'MsgBox strP & "\" & strF
createPivot strP & "\" & strF, strF
strF = Dir()
Loop
End Sub
Sub createPivot(path As String, fileName As String)
fileName = Replace(fileName, ".xlsx", "")
Dim appExcel As Excel.Application
Dim myWorkbook As Excel.Workbook
Set appExcel = CreateObject("Excel.Application")
Set myWorkbook = appExcel.Workbooks.Open(path)
appExcel.Visible = True
Sheets.Add
ActiveWorkbook.PivotCaches.Create(SourceType:=xlDatabase, SourceData:= _
fileName, Version:=6).CreatePivotTable TableDestination:= _
"Sheet1!R3C1", TableName:="PivotTable1", DefaultVersion:=6
Sheets("Sheet1").Select
Cells(3, 1).Select
With ActiveSheet.PivotTables("PivotTable1").PivotFields("Field1")
.Orientation = xlPageField
.Position = 1
End With
With ActiveSheet.PivotTables("PivotTable1").PivotFields("Field2")
.Orientation = xlPageField
.Position = 1
End With
With ActiveSheet.PivotTables("PivotTable1").PivotFields("Field3")
.Orientation = xlColumnField
.Position = 1
End With
ActiveSheet.PivotTables("PivotTable1").AddDataField ActiveSheet.PivotTables( _
"PivotTable1").PivotFields("FieldN"), "Sum of FieldN", xlSum
With ActiveSheet.PivotTables("PivotTable1").PivotFields("Field+1")
.Orientation = xlRowField
.Position = 1
End With
myWorkbook.Save
myWorkbook.Close
appExcel.Quit
Set myWorkbook = Nothing
Set appExcel = Nothing
Exit Sub
End Sub