Hi All,
I would like to share below codes with you. It works after one's own hear but I want to use same sheet for pivot table (for example Data1 or Data2), If I select some rows (for example between 1-5), run pivot table only for this rows. I also want to select where is locate the pivot table in Data1 or Data2 ( for example message box write B10). Lastly I want to use same macro for Data1 and Data2. I mean sometimes I have to use Data1, sometimes Data2. I hope My explanations are clear for you. I have already updated file. Could you please help me regarding this topic. Thank you in advance.
Sub MakePivotTable()
Dim pt As PivotTable
Dim strField As String
Dim WSD As Worksheet
Set WSD = Worksheets("Data1")
' Set WSD = Worksheets("Data2")
Dim PTOutput As Worksheet
Set PTOutput = Worksheets("Pivot")
Dim PTCache As PivotCache
Dim PRange As Range
' Find the last row with data
Dim finalRow As Long
finalRow = WSD.Cells(Application.Rows.Count, 1).End(xlUp).Row
' Find the last column with data
Dim finalCol As Long
finalCol = WSD.Cells(1, Application.Columns.Count).End(xlToLeft).Column
' Find the range of the data
Set PRange = WSD.Cells(1, 1).Resize(finalRow, finalCol)
Set PTCache = ActiveWorkbook.PivotCaches.Add(SourceType:=xlDatabase, SourceData:=PRange)
'delete previous pivot
Sheets("Pivot").Select
Columns("A:C").Select
Selection.Delete Shift:=xlToLeft
Range("A1").Select
' Create the pivot table
Set pt = PTCache.CreatePivotTable(TableDestination:=PTOutput.Cells(1, 1), _
TableName:="SamplePivot")
' Define the layout of the pivot table
' Set update to manual to avoid recomputation while laying out
pt.ManualUpdate = True
' Set up the row fields
pt.AddFields RowFields:=Array( _
"Cost")
' Set up the data fields
With pt.PivotFields("Expense1")
.Orientation = xlDataField
.Function = xlSum
.Position = 1
End With
' Set up the data fields
With pt.PivotFields("Expense2")
.Orientation = xlDataField
.Function = xlSum
.Position = 1
End With
' Set up the data fields
With pt.PivotFields("Expense3")
.Orientation = xlDataField
.Function = xlSum
.Position = 1
End With
' Now calc the pivot table
pt.ManualUpdate = False
End Sub
Bookmarks