2016-07-11 8 views
0

ブックが70枚あります。各シートが作成され、名前が付けられ、フィルタを使用して対応するデータをワークシートに挿入します。データ範囲は毎週変更される可能性があります。私は、すべての作業を行うためのVBAプログラムを作成しましたが、ユニークなフィルタリングされたデータを使用して各ワークシート内にピボットテーブルを作成しました。 私の質問は、forループ内の各ワークシート内にピボットテーブルを作成するにはどうすればいいですか?私は以下の私のコードの問題は、コードのソースデータのセクションであることを控除しました。各タブのデータ範囲は異なります(列は同じですが行数は異なります)。 ピボットテーブルの名前をループ内で繰り返す必要がありますか?forループ内でピボットテーブルを作成するvba

Sub Ptloop() 

dim x as long 
dim SorceRange as Range 
dim k as long 
'start of first generated work sheet 
x=4 
'number of worksheets 
k=75 


Set SourceRange = Range("A4", ActiveCell.End(xlDown).End(xlToRight)) 

For Each Worksheet In ActiveWorkbook.Sheets 
If x <= k Then 

ActiveWorkbook.PivotCaches.Create(SourceType:=xlDatabase, SourceData:= _ 
    Sheets(x).SourceRange, Version:=xlPivotTableVersion14). _ 
    CreatePivotTable TableDestination:=Sheets(x).Cells(4, 21), TableName:="PivotTable3", DefaultVersion _ 
    :=xlPivotTableVersion14 
x = x + 1 
Else 
Exit For 
End If 
Next Worksheet 
End Sub 
+0

ダイナミックレンジを使用する必要があります。この記事「マクロを使った動的範囲の作成」(http://www.contextures.com/xlNames03.html#Pivot) – skkakkar

+0

'For Loop'の中に' SourceRange'セットを持ち込み、それを 'ws'に修飾してください。したがって、Set SourceRange = Worksheet.Range( "A4"、Worksheet.Range( "A4")l.End(xlDown).End(xlToRight)) '。あなたがそれらを異なっていたい場合は、 'PivoTable&x'で各PTに名前を付けることができます。彼らはすべて別のシートにある場合は、しかし、それは必要ではありません。 –

答えて

0

ありオフコードをスローすることができる点がいくつかあり、またはあまりにも可能性を秘めています。

プログラムのメンテナンスを容易にするため、以下のリファクタリングされたコードを参照してください。

Option Explicit 'this forces variable declaration and is a "must use" programming tool 

Sub Ptloop() 

Dim ws as Worksheet 'make sure to qualify the worksheet to a variable 
         'using `Worksheet` could be problematic since its a reserved word in Excel for the `Worksheet` object itself 

Dim SourceRange as Range 

For Each ws In ThisWorkbook.Worksheets 'if you have a chart or macro sheet in your workbook `Sheets` will produce an error, if you only need actual Worksheets, use that directly 

    If ws.Index > 3 Then 'use the index property, you only want worksheets after sheet 3 

     With ws 'work directly with the object and assignment parentage to all objects 

      'set the range inside the loop to capture the data for that specific sheet 
      Set SourceRange = .Range("A4", .Range("A4").End(xlDown).End(xlToRight)) 

      'ActiveWorkbook may or may not refer to the workbook you really want to work with .. ThisWorkbook refers to the book running the code 
      ThisWorkbook.PivotCaches.Create(SourceType:=xlDatabase, SourceData:=SourceRange, Version:=xlPivotTableVersion14). _ 
       CreatePivotTable TableDestination:=.Cells(4, 21), TableName:="PivotTable" & ws.Index, DefaultVersion _ 
       :=xlPivotTableVersion14 

     End With 

    End If 

Next ws 

End Sub 
+0

パーフェクト!どうもありがとうございます。私はSourceRangeの部分で多くの問題を抱えていました。 ws.Indexを使って頂きありがとうございます。私のマクロは大幅に簡素化されました。ありがとう、トン。 – mmayfield

関連する問題