【发布时间】:2019-11-01 21:42:51
【问题描述】:
“c:”中有一些 xlsx 文件,是从 Microsoft Access 表中导出的。大约有 4 个文件,其列数和名称相同,但数据不同。
当代码开始运行时,它使第一个 xlsx 正确旋转没有问题,但第二次迭代在这里导致错误:
ActiveWorkbook.PivotCaches.Create(SourceType:=xlDatabase, SourceData:= _
fileName, Version:=6).CreatePivotTable TableDestination:= _
"Sheet1!R3C1", TableName:="PivotTable1", DefaultVersion:=6
错误:运行时错误“91”:对象变量或未设置块变量
在Sheets、ActiveWorkbook 等之前我已经尝试过使用“myWorkbook”,但是没有用或者我没有正确使用。
所有 Excel 文件都应该有数据透视表。
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
【问题讨论】:
-
“导致错误” 错误在哪一行? • 您的问题很可能是因为使用了
ActiveSheet和Select:How to avoid using Select in Excel VBA。 -
请edit您的问题并将所有其他信息放在那里。 cmets 中的代码不可读。还要尝试完成我发布的链接中的建议。这很有可能已经解决了您的问题。
标签: excel vba ms-access pivot-table