Excel VBA 数据透视缓存类型不匹配 运行-时间错误“13”

Excel VBA Pivot Cache Type Mismatch Run-Time Error '13'

感谢您对此的任何意见。我正在尝试制作一个简单的数据透视表 table,它从 sheet“5 月 15 日的 5 月趋势”中获取数据并将其放入我的数据透视表 Table sheet 中,称为 "Errors By Criticality - Pivot"。

当我尝试使用创建方法设置数据透视缓存范围时,它返回类型不匹配的运行时错误。我检查了参数,看起来我设置正确。我确实尝试指定 PivotTable 版本,但仍然遇到相同的错误。我的代码如下。

我假设这与 pvtCache 变量或我将其设置为范围的方式有关,但我想不出任何解决方案。

Sub PivotTableCode()

Dim pvtCache As PivotCache 
Dim pvt As PivotTable
Dim pf As PivotField
Dim pi As PivotItem 
'Set the cache of the pivot table
Sheets("5 Month Trending May 15").Select
Set pvtCache = ActiveWorkbook.PivotCaches.Create(xlDatabase, Range("A2:H38"))

'create the Pivot Table
Sheets("Errors by Criticality - Pivot").Select
Set pvt = ActiveSheet.PivotTables.Add(pvtCache, Range("AP2"), "MyPivotTable") 
End Sub

documentation for PivotCaches.Create表示

The SourceData argument is required if SourceType isn't xlExternal. It can be a Range object (when SourceType is either xlConsolidation or xlDatabase) or an Excel Workbook Connection object (when SourceType is xlExternal).

尽管如此,宏录制器总是会在此处为 SourceData 创建一个 String(It will even create a bad string if the Sheet has a space in the name).

鉴于对宏记录器的偏好,我经常将其作为 String 地址提供。

我之前能够在这里提供 Range,所以我不确定在这种情况下具体发生了什么阻止了 Range 的使用。

要使用 String,您的代码应如下所示:

Set pvtCache = ActiveWorkbook.PivotCaches.Create(xlDatabase, "'5 Month Trending May 15'!A2:H38")