VBA Code for creating a pivot table

morz68

New Member
Joined
May 6, 2012
Messages
32
Hi

I have tried recording, and looking through google and editing code. But for the life of me I can't get my button to work.

I just want to:

1. Select current range
2. Create Pivot Table on a new sheet
3. Put one field in row
4. Put one field in column

I thought recording would be easy, but it doesn't work. :)
 

Excel Facts

Bring active cell back into view
Start at A1 and select to A9999 while writing a formula, you can't see A1 anymore. Press Ctrl+Backspace to bring active cell into view.
Hello morz68, try the below code ... Note that you have to select the range of data first before running the code

Code:
Sub Create_Pivot()

Dim Rg As Range
Set Rg = Selection

Sheets.Add After:=Sheets(Sheets.Count)

ActiveWorkbook.PivotCaches.Create(SourceType:=xlDatabase, SourceData:=Rg).CreatePivotTable _
    TableDestination:=Sheets(Sheets.Count).Name & "!R3C1", TableName:="PVT1"

With ActiveSheet.PivotTables("PVT1")
    .PivotFields(1).Orientation = xlColumnField
    .PivotFields(2).Orientation = xlRowField
End With

End Sub
 
Last edited:
Upvote 0
That's fantastic, I did get a solution with recording (not sure why it didn't work at first?)

Can you suggest any way to have the data selected before. I'm currently, Ctrl+Shift+Down Arrow and Right Arrow?

Thanks again
M:)
 
Upvote 0
Perhaps changing the range defining to this

Code:
Set Rg = ActiveSheet.UsedRange
 
Upvote 0

Forum statistics

Threads
1,223,885
Messages
6,175,180
Members
452,615
Latest member
bogeys2birdies

We've detected that you are using an adblocker.

We have a great community of people providing Excel help here, but the hosting costs are enormous. You can help keep this site running by allowing ads on MrExcel.com.
Allow Ads at MrExcel

Which adblocker are you using?

Disable AdBlock

Follow these easy steps to disable AdBlock

1)Click on the icon in the browser’s toolbar.
2)Click on the icon in the browser’s toolbar.
2)Click on the "Pause on this site" option.
Go back

Disable AdBlock Plus

Follow these easy steps to disable AdBlock Plus

1)Click on the icon in the browser’s toolbar.
2)Click on the toggle to disable it for "mrexcel.com".
Go back

Disable uBlock Origin

Follow these easy steps to disable uBlock Origin

1)Click on the icon in the browser’s toolbar.
2)Click on the "Power" button.
3)Click on the "Refresh" button.
Go back

Disable uBlock

Follow these easy steps to disable uBlock

1)Click on the icon in the browser’s toolbar.
2)Click on the "Power" button.
3)Click on the "Refresh" button.
Go back
Back
Top