2017-01-28 7 views
1

ピボットテーブルを自動的に取得するために、このコードをマクロレコーダーで作成しました。記録ピボット作成マクロ(VBA)に無効な参照があるのはなぜですか?

しかし、私は再びこのコードを実行すると、エラーメッセージが表示されます。

実行時エラー1004:この行 Workbooks("works.xlsm").Connections.Add2で無効な参照

このコードが記録された場合、なぜ無効な参照がありますか?記録中に、私はテーブル(R1C4:R18532C9)の名前 "データベース"を与えました。私は説明がコメントとしてコード内にある、Windowsの10およびOffice 2016

Range("D1").Select 
Range(Selection, Selection.End(xlToRight)).Select 
Range(Selection, Selection.End(xlDown)).Select 
ActiveWorkbook.Names.Add Name:="database", RefersToR1C1:= _ 
    "=Data!R1C4:R18532C9" 
ActiveWorkbook.Names("database").Comment = "" 
Range("D1").Select 
Workbooks("works.xlsm").Connections.Add2 _ 
    "WorksheetConnection_works.xlsm!database", "", _ 
    "WORKSHEET;C:\Users\gabor\Documents\CAFM\VBS\works.xlsm", _ 
    "works.xlsm!database", 7, True, False 
ActiveWorkbook.PivotCaches.Create(SourceType:=xlExternal, SourceData:= _ 
    ActiveWorkbook.Connections("WorksheetConnection_works.xlsm!database"), _ 
    Version:=6).CreatePivotTable TableDestination:="Pivot!R1C1", TableName:= _ 
    "Statement1", DefaultVersion:=6 
Sheets("Pivot").Select 
Cells(1, 1).Select 
With ActiveSheet.PivotTables("Statement1").CubeFields("[database].[Person]") 
    .Orientation = xlRowField 
    .Position = 1 
End With 

The database table and the pivot results with xlCount and xlDistinctCount

enter image description here

+2

追加しようとすると、接続は既に存在しますか? – OldUgly

+0

行が実行された時点で "works.xlsm"が開いていますか? – YowE3K

+0

コードを一度実行すると、 'PivotTable'がすでに作成されており、' Connection'も作成されています。したがって、コードを2回目に実行するときは、 'PivotCache'をリフレッシュし、その後、更新された' PivotCache'で 'PivotTable'をリフレッシュする必要があります。 –

答えて

0

私はworks.xlsm」からConnections.Add2でCommandTextをパラメータを変更!データベース "を"データ!データベース "に変更します。それは問題を解決しました。私はActiveWorkbook.Names.Addも編集しました。

LastRow = Sheets("Data").Cells(Rows.Count, 1).End(xlUp).Row 
LastCol = Sheets("Data").Cells(1, Columns.Count).End(xlToLeft).Column 

ActiveWorkbook.Names.Add _ 
     Name:="database", _ 
     RefersTo:="=Data!R1C4:R" & LastRow & "C" & LastCol & "" 

ActiveWorkbook.Connections.Add2 _ 
    "WorksheetConnection_works.xlsm!database", "", _ 
    "WORKSHEET;C:\Users\gabor\Documents\CAFM\VBS\works.xlsm", _ 
    "Data!database", 7, True, False 

ActiveWorkbook.PivotCaches.Create(SourceType:=xlExternal, SourceData:= _ 
    ActiveWorkbook.Connections("WorksheetConnection_works.xlsm!database"), _ 
    Version:=6).CreatePivotTable TableDestination:="Pivot!R1C1", TableName:= _ 
    "Statement1", DefaultVersion:=6 
Sheets("Pivot").Select 
Cells(1, 1).Select 
With ActiveSheet.PivotTables("Statement1").CubeFields("[database].[Person]") 
    .Orientation = xlRowField 
    .Position = 1 
End With 

私はこのコードでxlDistinctCountを得ることができる:

ActiveSheet.PivotTables("Statement1").CubeFields.GetMeasure "[database].[TT]" _ 
    , xlCount 
ActiveSheet.PivotTables("Statement1").AddDataField ActiveSheet.PivotTables(_ 
    "Statement1").CubeFields("[Measures].[quantity of items - TT]") 
With ActiveSheet.PivotTables("Statement1").PivotFields(_ 
    "[Measures].[quantity of items - TT]") 
    .Caption = "number of distinct items – TT" 
    .Function = xlDistinctCount 
End With 

私が最初にxlCountを使用していたし、この結果に私はxlDistinctCountを得ることができます。

1

は、以下のコードを編集してみてください。

xlDistinctCountはOffice 2010を持っているため、テストされていませんが、それは機能するはずです。ピボット・テーブルの

コード

Option Explicit 

Sub AutoDynamicPivot() 

Dim PT     As PivotTable 
Dim PTCache    As PivotCache 

Dim WB     As Workbook 
Dim Sht     As Worksheet 

Dim SrcData    As Variant 
Dim lRow    As Long, lCol  As Long 

Set WB = ThisWorkbook 
Set Sht = WB.Worksheets("Data") '<-- set the "Data" worksheet 

lRow = Sht.Range("A1").End(xlDown).Row '<-- modifed from "D1" to "A1" (according to PO screen-shot) 
lCol = Sht.Range("A1").End(xlToRight).Column '<-- modifed from "D1" to "A1" (according to PO screen-shot) 

' set the Named Range "database" to the data in worksheet "Data" 
WB.Names.Add Name:="database", RefersToR1C1:="=" & Sht.Name & "!R1C1:R" & lRow & "C" & lCol '<-- modifed to "R1C1" (according to PO screen-shot) 
WB.Names("database").Comment = "" 

' Determine the data range you want for your Pivot Cache 
Set SrcData = Range("database") 

' set the Pivot Cache 
Set PTCache = ActiveWorkbook.PivotCaches.Add(xlDatabase, SrcData) 

' add this line in case the Pivot table doesn't exit >> first time running this Macro 
On Error Resume Next 
Set PT = Worksheets("Pivot").PivotTables("Statement1") ' check if "Statement1" Pivot Table already created (in past runs of this Macro) 

On Error GoTo 0 
If PT Is Nothing Then 

    ' create a new Pivot Table in "Pivot" sheet, start from Cell A1 
    Set PT = Worksheets("Pivot").PivotTables.Add(PivotCache:=PTCache, TableDestination:=Worksheets("Pivot").Range("A1"), TableName:="Statement1") 

    'Create the headings and row and column orientation and all of your other settings here 
    With PT 
     ' set "Person" as rows field 
     With .PivotFields("Person") 
      .Orientation = xlRowField 
      .Position = 1 
     End With 

     ' set "Month" as Filter 
     With .PivotFields("Month") 
      .Orientation = xlPageField 
      .Position = 1 
     End With 

     ' set "Count of Cases" 
     .AddDataField .PivotFields("Case"), "Count of Case", xlCount 

     ' set "Distinct Count of Cases" 
     .AddDataField .PivotFields("Case"), "Distinct Count of Case", xlDistinctCount 
    End With 
Else 
    ' just refresh the Pivot cache with the updated Range (data in "Data" worksheet) 
    PT.ChangePivotCache PTCache 
    PT.RefreshTable 
End If 

End Sub 

スクリーンショットこのコードで作成:

enter image description here

+0

この部分はどこですか?:ワークブック( "works.xlsm")Connections.Add2 .Function = xlDistinctCountの作成に必要です。 – vega69

+0

@ vega69なぜそれが必要ですか?これは、ソースデータをピボットキャッシュに取り込む別の方法です。この機能は何をすると思われますか?どのフィールド名を数えたいですか? –

+0

データベースでは、すべてのケースが人によって収集されます。人によって症例数を数えたい場合は、.Function = xlCountを使用できます。例えば、John Doは、1月に12件を解決したことを意味します。しかし、異なるケースの数量を数えたい場合は、.Function = xlDistinctCountを使用する必要があります。例えば、John Doは4種類のケース(Type1 = 2pcs、Type2 = 3pcs、Type3 = 3pcs、Type4 = 4pcs、合計= 12)。この(xlDistinctCount)を取得するには、ワークブック( "works.xlsm")を使用する必要があります。Connections.Add2 – vega69

関連する問題