我的Excel VBA程序包含以下函数,它会多次调用。在函数中调用的PivotCaches.Create函数在之前的实例上正常工作之后,第四次或第五次调用函数时会引发运行时错误(13)。
Function CreateSomePivots(ByVal wb As Workbook, _ 'Workbook to use for pivots
ByVal srcn As String, _ 'Name of source worksheet with data table
ByVal destn As String, _ 'Name of destination worksheet on which to store pivots
ByRef pts As PivotTable, _ 'Array in which to store pivot tables
Optional ByVal orgVar As String = "Assigned Org", _ 'Name of assigned org variable
Optional ByVal emplidVar As String = "Employee Emplid", _ 'Name of employee ID variable
Optional ByVal byVar As String = "", _ 'Variable to compare groups on
Optional ByVal regHires As Boolean = False) _ 'Filters on regular hires
As Boolean 'Returns True if new worksheet created
Dim ps As Worksheet 'Sheet with pivot tables
Dim src As Worksheet 'Source worksheet with data table
Dim loc As String 'Location
Dim pc As PivotCache 'Pivot cache
Dim pi As PivotItem 'Pivot item
Dim i As Integer 'Iterate through groups
On Error Resume Next
Set ps = wb.Sheets(destn)
Set src = wb.Sheets(srcn)
On Error GoTo 0
If ps Is Nothing Then
wb.Activate
Set ps = Sheets.Add(Before:=src)
ps.name = destn
loc = "'destn'!" & Range("A3").Address(ReferenceStyle:=xlR1C1)
Set pc = ActiveWorkbook.PivotCaches.Create(SourceType:=xlDatabase, _
SourceData:=Sheets(srcn).ListObjects(1).Range, _
Version:=xlPivotTableVersion15)
Set pts(0) = pc.CreatePivotTable(loc)
...
CreateSomePivots = True
End If
CreateSomePivots = False
End Function
我检查了传递给函数的所有参数,并尝试操作函数调用。似乎没有什么不对,但我似乎无法摆脱错误。