以下のコードを実行すると、不一致エラー 13 が発生します。コード モジュール全体が使用されており、1 年以上ほとんど変更されていません。私は最近何も変更していません。このワークブックのユーザーは私だけです。
動かないコード:
Private Sub CreateMIAPivots(MIABook As Workbook, MIASheet As Worksheet, MaxRow As Long)
Dim wksPivotSheet As Worksheet
Dim PivotRange As Range
Set wksPivotSheet = MIABook.Sheets.Add
wksPivotSheet.Name = "Summary"
wksPivotSheet.Tab.Color = RGB(255, 0, 0)
Set PivotRange = MIASheet.Range("A1:Y" & MaxRow)
With MIABook.PivotCaches.Add(xlDatabase, PivotRange) 'Error sets here
'More code below
MaxRow
は可変ですが、約 600 行から約 7,000 行のファイルに対してチェックしましたRange
。他の方法で操作しようとすると、オブジェクトは有効な参照を作成しています。
SOに関するいくつかの関連する質問をここで確認しました:
- 私は2003年にしか働いていませんが、とにかくエラーは異なります。
PivotCaches
新しいワークブックを作成する前に、ワークブックに他のワークブックがないことを確認しました。- ここで受け入れられたソリューションを使用して、この作業に成功しました:名前付き範囲を使用する (以下のフォローアップ コードを参照)
回避策コード:
Private Sub CreateMIAPivots(MIABook As Workbook, MIASheet As Worksheet, MaxRow As Long)
Dim wksPivotSheet As Worksheet
Dim pc As PivotCache
Dim lVBAVer As Long
Dim PivotRange As Range
lVBAVer = CLng(Application.Version)
Set wksPivotSheet = MIABook.Sheets.Add
wksPivotSheet.Name = "Summary"
wksPivotSheet.Tab.Color = RGB(255, 0, 0)
Set PivotRange = MIASheet.Range("A1:Y" & MaxRow)
MIABook.Names.Add Name:="PivotRange", RefersTo:=PivotRange
'Using answer from https://stackoverflow.com/a/11868231/698590 (StackOverflow)
'as a guide for version checking. Original answer of
'CLng(Application.VBE.Version) did not work here.
#If lVBAVer <= 11 Then
Set pc = MIABook.PivotCaches.Add(xlDatabase, "PivotRange")
#Else
Set pc = MIABook.PivotCaches.Create(xlDatabase, "PivotRange")
#End If
With pc
'More code below
私の質問は、なぜ上記の解決策が必要なのですか? 最初のように使用中に完全に機能するコードが突然停止したのは私だけではないPivotCaches
ようです。では、ここでの本当の根本原因は何ですか? コードが機能しなくなった原因は何ですか?
可能であれば、将来の予期しないエラーの発生を防ぐことができるようにしたいと思います。答えがコード/ワークブックのどこかで行ったことにある可能性があることはわかっていますが (ここでは参照されていません)、何が変更されたかを追跡することはできません。