+ Reply to Thread
Results 1 to 12 of 12

Macro to create a pivot with variable rows.

Hybrid View

  1. #1
    Forum Contributor
    Join Date
    03-25-2011
    Location
    London, England
    MS-Off Ver
    office 2021
    Posts
    317

    Macro to create a pivot with variable rows.

    Hi Guys

    I am attempting to create a Macro which will create a pivot. I intend to place a button on the screen so others can run it.

    I have researched the net and come up with the following solution
    Sub CreatePivot()
    '
    ' CreatePivot Macro
    '
    
           FianlRow = Cells(Rows.Count, 1).End(xlUp).Row
        DataSheet = ActiveSheet.Name
        NewSheet = ActiveSheet.Name
        ActiveCell.Offset(39, 1).Range("A1").Select
        Sheets.Add
         NewSheet = ActiveSheet.Name
        ActiveWorkbook.PivotCaches.Create(SourceType:=xlDatabase, SourceData:= _
            DataSheet & "!R2C1:R & FinalRow & C17", Version:=xlPivotTableVersion14). _
            CreatePivotTable TableDestination: NewSheet & "!R3C1", TableName:="PivotTable2",
          DefaultVersion:=xlPivotTableVersion14
        Sheets(NewSheet).Select
    Then carries on with the actual manipulation within the pivot. This part does not work for me. I have not found a solution in this forum but I am sure that you will immediately see where the problem is. I got this from http://www.youtube.com/watch?v=UkPxhlW9Hd0

    Have uploaded the file.

    Any suggestions would be great.

    Thanks
    Mark
    Attached Files Attached Files
    Last edited by markDuffy; 02-22-2013 at 09:31 AM.

  2. #2
    Forum Contributor arlu1201's Avatar
    Join Date
    09-09-2011
    Location
    Bangalore, India
    MS-Off Ver
    Excel 2003 & 2007
    Posts
    19,166

    Re: Macro to create a pivot with variable rows.

    Your post does not comply with Rule 3 of our Forum RULES. Use code tags around code.

    Posting code in [CODE] [/CODE] tags makes your code much easier to read and copy for testing, it also maintains VBA formatting.

    Highlight your code and click the # icon at the top of your post window. More information about these and other tags can be found here
    If I have helped, Don't forget to add to my reputation (click on the star below the post)
    Don't forget to mark threads as "Solved" (Thread Tools->Mark thread as Solved)
    Use code tags when posting your VBA code: [code] Your code here [/code]

  3. #3
    Forum Contributor
    Join Date
    03-25-2011
    Location
    London, England
    MS-Off Ver
    office 2021
    Posts
    317

    Re: Macro to create a pivot with variable rows.

    Thanks have doe that using Edit. just waiting now to see if its gone through.

  4. #4
    Forum Contributor arlu1201's Avatar
    Join Date
    09-09-2011
    Location
    Bangalore, India
    MS-Off Ver
    Excel 2003 & 2007
    Posts
    19,166

    Re: Macro to create a pivot with variable rows.

    Try changing
    SourceData:= _
            DataSheet & "!R2C1:R & FinalRow & C17"
    to
    SourceData:= _
            DataSheet & "!R2C1:R" & FinalRow & "C17"

  5. #5
    Forum Contributor
    Join Date
    03-25-2011
    Location
    London, England
    MS-Off Ver
    office 2021
    Posts
    317

    Re: Macro to create a pivot with variable rows.

    Hi Administrator
    Just about to republish with that exact change. I had not copied it correctly form the video. But a line below and I am still getting a Compile Error
    Expected:expression.
    TableDestination:NewSheet & "!R3C1", TableName:="PivotTable2",
          DefaultVersion:=xlPivotTableVersion14
    here it highlights the & after new sheet. Should i republish the updated excel?
    Thanks
    Mark

  6. #6
    Forum Contributor arlu1201's Avatar
    Join Date
    09-09-2011
    Location
    Bangalore, India
    MS-Off Ver
    Excel 2003 & 2007
    Posts
    19,166

    Re: Macro to create a pivot with variable rows.

    Change
    TableDestination:NewSheet
    to
    TableDestination:=NewSheet

  7. #7
    Forum Expert romperstomper's Avatar
    Join Date
    08-13-2008
    Location
    East Sussex, UK
    MS-Off Ver
    365, varying versions/builds
    Posts
    21,377

    Re: Macro to create a pivot with variable rows.

    Your original code has a typo at the start:
           FianlRow = Cells(Rows.Count, 1).End(xlUp).Row
    should be
           FinalRow = Cells(Rows.Count, 1).End(xlUp).Row
    Option Explicit would have caught that! Also you should enclose the sheet name in single quotes.

  8. #8
    Forum Contributor
    Join Date
    03-25-2011
    Location
    London, England
    MS-Off Ver
    office 2021
    Posts
    317

    Re: Macro to create a pivot with variable rows.

    Hi Guys

    Thanks again.

    Seriously embarrassed that on two occasions I am being corrected for what appears to be an inability to copy as all the above are in the example I was shown in the Video mentioned at the top. Not an excuse but I am dyslexic which partly means that I see things as I want to see them or that's my take. 69 can look like 96 all day long.

    I have gone over it again and again to see if there is a basic mistake. I can't see one if there is so I am uploading it. I know that it will eventually work as I have always succeeded her on this forum.

    All the best
    Mark
    Attached Files Attached Files

  9. #9
    Forum Expert romperstomper's Avatar
    Join Date
    08-13-2008
    Location
    East Sussex, UK
    MS-Off Ver
    365, varying versions/builds
    Posts
    21,377

    Re: Macro to create a pivot with variable rows.

    Try this:
    Sub CreatePivot()
        Dim PT              As Excel.PivotTable
        Dim PC              As Excel.PivotCache
        Dim FinalRow        As Long
        Dim DataSheet       As String
        Dim NewSheet        As String
        Dim vItem
        Dim vCurrItems
        
        vCurrItems = Array("Rate", "Supplier", "Internal", "External", "Total", "Profit", "Quote")
        Const sCURR_FORMAT As String = "_-[$£-809]* #,##0.00_-;-[$£-809]* #,##0.00_-;_-[$£-809]* ""-""??_-;_-@_-"
        
        Application.ScreenUpdating = False
        With Sheets("Segmentise  cost")
            FinalRow = .Cells(.Rows.Count, 1).End(xlUp).Row
            DataSheet = .Name
        End With
        NewSheet = Sheets.Add.Name
        
        Set PC = ActiveWorkbook.PivotCaches.Create(SourceType:=xlDatabase, _
                        SourceData:="'" & DataSheet & "'!R2C1:R" & FinalRow & "C17", _
                        Version:=xlPivotTableVersion14)
        
        Set PT = PC.CreatePivotTable(TableDestination:="'" & NewSheet & "'!R3C1", _
                        TableName:="PivotTable2", DefaultVersion:=xlPivotTableVersion14)
        
        With PT
            .ManualUpdate = True
            With .PivotFields("Order 2")
                .Orientation = xlRowField
                .Position = 1
            End With
            .AddDataField .PivotFields("Order"), "-Order", xlSum
            .AddDataField .PivotFields("Int/Ex"), "-Int/Ex", xlSum
            .AddDataField .PivotFields("Phase"), "-Phase", xlSum
            .AddDataField .PivotFields("Country"), "-Country", xlSum
            .AddDataField .PivotFields("Options"), "-Options", xlSum
            .AddDataField .PivotFields("Days"), "-Days", xlSum
            .AddDataField .PivotFields("Respd."), "-Respd.", xlSum
            .AddDataField .PivotFields("Staff"), "-Staff", xlSum
            For Each vItem In vCurrItems
                With .PivotFields(vItem)
                    .Caption = "-" & vItem
                    .Orientation = xlDataField
                    .Function = xlSum
                    .NumberFormat = sCURR_FORMAT
                End With
            Next vItem
            With .PivotFields("Order 2")
                .PivotItems("(blank)").Visible = False
                .AutoSort xlAscending, "-Order", PT.PivotColumnAxis.PivotLines(1), 1
            End With
            .ManualUpdate = False
        End With
        ActiveWorkbook.ShowPivotTableFieldList = False
        Cells.EntireColumn.AutoFit
        Application.ScreenUpdating = True
    End Sub
    Everyone who confuses correlation and causation ends up dead.

  10. #10
    Forum Contributor
    Join Date
    03-25-2011
    Location
    London, England
    MS-Off Ver
    office 2021
    Posts
    317

    Re: Macro to create a pivot with variable rows.

    Hi Romperstomper

    It is absolutely beautiful. My next need was how to have the same do multiple pivots in the same workbook but this already does that. I did have one small issue where the sorting and ascending caused an error. So I have removed this and it works fantastic. I can handle that at the bottom.

    Removed from macro
    With .PivotFields("Order 2")
                .PivotItems("(blank)").Visible = False
                .AutoSort xlAscending, "-Order", PT.PivotColumnAxis.PivotLines(1), 1
            End With
    I am now going to spend most of the weekend working out how it all works as your code is half the length of mine which I had made no attempt to shorten. But if you have time could you please heavily comment this. It will really help to understand it. But thanks again and again. It is fabulous.

    Education comes from the Latin and means to the lead through. Learning is so much quicker when we don’t have to keep reinventing the wheal.

    Have a great day

    Mark

  11. #11
    Forum Expert romperstomper's Avatar
    Join Date
    08-13-2008
    Location
    East Sussex, UK
    MS-Off Ver
    365, varying versions/builds
    Posts
    21,377

    Re: Macro to create a pivot with variable rows.

    Revised version with comments and the sorting issue fixed:
    Sub CreatePivot()
        Dim PT              As Excel.PivotTable
        Dim PC              As Excel.PivotCache
        Dim FinalRow        As Long
        Dim DataSheet       As String
        Dim NewSheet        As String
        Dim vItem
        Dim vCurrItems
        
        ' this is an array of the currency fields
        vCurrItems = Array("Rate", "Supplier", "Internal", "External", "Total", "Profit", "Quote")
        ' number format to apply to the fields listed above
        Const sCURR_FORMAT As String = "_-[$£-809]* #,##0.00_-;-[$£-809]* #,##0.00_-;_-[$£-809]* ""-""??_-;_-@_-"
        ' turn off screen updating to speed code up
        Application.ScreenUpdating = False
        
        With Sheets("Segmentise  cost")
            ' get last used row in col A on data sheet
            FinalRow = .Cells(.Rows.Count, 1).End(xlUp).Row
            DataSheet = .Name
        End With
        ' add new sheet and store its name
        NewSheet = Sheets.Add.Name
        
        ' create the data cache
        Set PC = ActiveWorkbook.PivotCaches.Create(SourceType:=xlDatabase, _
                        SourceData:="'" & DataSheet & "'!R2C1:R" & FinalRow & "C17", _
                        Version:=xlPivotTableVersion14)
        ' create the pivot
        Set PT = PC.CreatePivotTable(TableDestination:="'" & NewSheet & "'!R3C1", _
                        TableName:="PivotTable2", DefaultVersion:=xlPivotTableVersion14)
        
        With PT
            ' prevent the pivot from updating while we're changing the layout, just to speed processing
            .ManualUpdate = True
            ' add row field
            With .PivotFields("Order 2")
                .Orientation = xlRowField
                .Position = 1
            End With
            ' add data fields, setting caption and using Sum function
            .AddDataField .PivotFields("Order"), "-Order", xlSum
            .AddDataField .PivotFields("Int/Ex"), "-Int/Ex", xlSum
            .AddDataField .PivotFields("Phase"), "-Phase", xlSum
            .AddDataField .PivotFields("Country"), "-Country", xlSum
            .AddDataField .PivotFields("Options"), "-Options", xlSum
            .AddDataField .PivotFields("Days"), "-Days", xlSum
            .AddDataField .PivotFields("Respd."), "-Respd.", xlSum
            .AddDataField .PivotFields("Staff"), "-Staff", xlSum
            
            ' loop through the currency fields adding them to the data area and formatting them
            For Each vItem In vCurrItems
                With .PivotFields(vItem)
                    .Caption = "-" & vItem
                    .Orientation = xlDataField
                    .Function = xlSum
                    .NumberFormat = sCURR_FORMAT
                End With
            Next vItem
            ' allow the pivot table to update so that we can sort
            .ManualUpdate = False
            
            With .PivotFields("Order 2")
                .PivotItems("(blank)").Visible = False
                .AutoSort xlAscending, "-Order", PT.PivotColumnAxis.PivotLines(1), 1
            End With
        End With
        'hide field list
        ActiveWorkbook.ShowPivotTableFieldList = False
        Cells.EntireColumn.AutoFit
        Application.ScreenUpdating = True
    End Sub

  12. #12
    Forum Contributor
    Join Date
    03-25-2011
    Location
    London, England
    MS-Off Ver
    office 2021
    Posts
    317

    Re: Macro to create a pivot with variable rows.

    Cheers it will still take the weekend to understand it but that will be a pleasure Thanks again

+ Reply to Thread

Thread Information

Users Browsing this Thread

There are currently 1 users browsing this thread. (0 members and 1 guests)

Bookmarks

Posting Permissions

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

Search Engine Friendly URLs by vBSEO 3.6.0 RC 1