Marco: Pivot Table

G

Guest

Hi folks,

The following is my macro to create pivot table. It works fine but I need
some help on the row range. For example, my new data source table have 100
rows and 3 columes. When I run the following macro, I will have wrong pivot
table because the range is "Sheet1!R1C1:R4C2". Could anyone tell me how to
change the range ("Sheet1!R1C1:R100C3") by itself?

Any help will be deeply appreciated.

Thanks in advance.

Tim.

Sub Macro1()
'
' Macro1 Macro
'

'
ActiveWorkbook.PivotCaches.Add(SourceType:=xlDatabase, SourceData:= _
"Sheet1!R1C1:R4C2").CreatePivotTable TableDestination:="",
TableName:= _
"PivotTable1", DefaultVersion:=xlPivotTableVersion10
ActiveSheet.PivotTableWizard TableDestination:=ActiveSheet.Cells(3, 1)
ActiveSheet.Cells(3, 1).Select
ActiveSheet.PivotTables("PivotTable1").AddFields RowFields:="State"

ActiveSheet.PivotTables("PivotTable1").PivotFields("Invoice").Orientation = _
xlDataField
End Sub
 
D

Debra Dalgleish

You can use a dynamic named range for the pivot source, and use that
name in the code. For example:

ActiveWorkbook.PivotCaches.Add(SourceType:=xlDatabase, SourceData:= _
"PivotRange").CreatePivotTable TableDestination:="", TableName:= _
"PivotTable1", DefaultVersion:=xlPivotTableVersion10

There are instructions for dynamic names here:

http://www.contextures.com/xlNames01.html#Dynamic
 
G

Guest

Debra,

Thanks a lot for your help.

Tim.

Debra Dalgleish said:
You can use a dynamic named range for the pivot source, and use that
name in the code. For example:

ActiveWorkbook.PivotCaches.Add(SourceType:=xlDatabase, SourceData:= _
"PivotRange").CreatePivotTable TableDestination:="", TableName:= _
"PivotTable1", DefaultVersion:=xlPivotTableVersion10

There are instructions for dynamic names here:

http://www.contextures.com/xlNames01.html#Dynamic
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top