VBAで元データ範囲の自動取得

 

Sub test()

   '  元データ範囲の自動取得

 

    Dim myR As Range
    ' A2を含むセル範囲を変数myRに代入
    Set myR = Sheets(1).Range("A1").CurrentRegion

End Sub

 

 

Sub test2()

    ' VBAでピボットテーブルを作成


    Dim WS As Worksheet
    Dim PVC As PivotCache
    Dim PVT As PivotTable
    
    Dim myR As Range
    ' 元データ範囲自動取得
    Set myR = Sheets(1).Range("A1").CurrentRegion
    
    ' ピボットテーブル出力シートを追加(最後に)
    Set WS = Sheets.Add(after:=Sheets(Sheets.Count))
    
    ' ピボットテーブルデータソースをセット
    Set PVC = ActiveWorkbook.PivotCaches.Add(SourceType:=xlDatabase, _
                                            SourceData:=myR)
    Set PVT = PVC.CreatePivotTable(TableDestination:=WS.Name & "!R3C1", _
                                            TableName:="ピボットテーブル1")
    ' フィールドのレイアウト設定
    With PVT
        With .PivotFields("地区")
            .Orientation = xlRowField
            .Position = 1
        End With
        With .PivotFields("支店名")
            .Orientation = xlRowField
            .Position = 2
        End With
        
        '   集計対象を設定
        .AddDataField .PivotFields("売上高"), "合計 / 売上高", xlSum
    End With


End Sub

 

 

 

― ― ― ― ― ― ― ― ― ― → Excel VBA基礎入門もくじ へ戻る 

 

 

参考記事