Consulting

Results 1 to 6 of 6

Thread: Pivot Table VBA

  1. #1
    VBAX Regular
    Joined
    Sep 2016
    Posts
    24
    Location

    Thumbs up Pivot Table VBA

    Hi guys,
    I want to create a pivot table without directly pointing out the names of the Pivot Fields, instead I want to refer to the cell value.
    Has anyone an idea how to do it??

    Range("A1:BQ22").Select
    Range("J8").Activate
    ActiveWorkbook.PivotCaches.Create(SourceType:=xlDatabase, SourceData:= _
    Sheets("DATA").Range("A1").CurrentRegion, Version:=xlPivotTableVersion14).CreatePivotTable _
    TableDestination:="Sheet2!R20C1", TableName:="PivotTable2", DefaultVersion _
    :=xlPivotTableVersion14

    ActiveSheet.PivotTables("PivotTable1").AddDataField ActiveSheet.PivotTables( _
    "PivotTable1").PivotFields(Cells(2, 28).Value), "Average" & Cells(2, 28).Value, xlAverage


    Thanks for your help!
    Step

  2. #2
    VBAX Expert
    Joined
    Sep 2016
    Posts
    788
    Location
    Option Explicit
    
    Sub test()
        Dim pvc As PivotCache
        Dim pvt As PivotTable
        Dim ws1 As Worksheet
        Dim ws2 As Worksheet
        
        Set ws1 = Worksheets("DATA")
        Set ws2 = Worksheets("Sheet2")
        
         Set pvc = ActiveWorkbook.PivotCaches.Create( _
                    SourceType:=xlDatabase, _
                    SourceData:=ws1.Range("A1").CurrentRegion)
                    
        Set pvt = pvc.CreatePivotTable(TableDestination:=ws2.Range("A20"))
    
    
       With pvt
            .AddDataField Field:=.PivotFields(ws1.Cells(1, 4).Value), _
                        Caption:="Average" & ws1.Cells(1, 4).Value, _
                        Function:=xlAverage
        End With
        
    End Sub

  3. #3
    VBAX Regular
    Joined
    Sep 2016
    Posts
    24
    Location
    sb

  4. #4
    VBAX Regular
    Joined
    Sep 2016
    Posts
    24
    Location
    Thanks for this code looks reasonable! But I get a type error for the lines set pvc=ActiveWorkbook.PivotCaches.Create etc
    ... can anyone explain why?? Thanks, Jens

  5. #5
    VBAX Expert
    Joined
    Sep 2016
    Posts
    788
    Location
    Please try once more with my sample file.

    20160925VBA_EXPRESS.xlsx

  6. #6
    VBAX Regular
    Joined
    Sep 2016
    Posts
    24
    Location
    Is Working now, my code for transforming into a table was not correct, Thanks mana for your help. Really appreciate it!

Tags for this Thread

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •