1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

vbaで日ポッドテーブルの作成

Posted at
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

1
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?