Sub CreatePivotTable()
Dim pivotCache As PivotCache
Dim pivotTable As PivotTable
Dim startPivot As String
Dim wsSource As Worksheet
Dim wsDest As Worksheet
Dim dataRange As Range
Dim pivotRange As Range
' データソースと出力先のシートを設定
Set wsSource = ThisWorkbook.Sheets("Sheet1")
Set wsDest = ThisWorkbook.Sheets("Sheet2")
' データ範囲とピボットテーブルの配置先を設定
Set dataRange = wsSource.Range("A1").CurrentRegion ' A1から連続するデータ範囲を自動で選択
startPivot = "A3" ' ピボットテーブルの開始位置をSheet2のA3に設定
' ピボットキャッシュを作成
Set pivotCache = ThisWorkbook.PivotCaches.Create( _
SourceType:=xlDatabase, _
SourceData:=dataRange)
' ピボットテーブルを作成
Set pivotTable = pivotCache.CreatePivotTable( _
TableDestination:=wsDest.Range(startPivot), _
TableName:="NewPivotTable")
' ピボットテーブルのフィールドを設定
With pivotTable
' 例: "Field1"を行フィールドに、"Field2"を値フィールドに設定
.PivotFields("Field1").Orientation = xlRowField
.PivotFields("Field1").Position = 1
.PivotFields("Field2").Orientation = xlDataField
.PivotFields("Field2").Function = xlSum
.PivotFields("Field2").Position = 1
End With
End Sub
More than 1 year has passed since last update.
Register as a new user and use Qiita more conveniently
- You get articles that match your needs
- You can efficiently read back useful information
- You can use dark theme