Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.1k views
in Technique[技术] by (71.8m points)

excel - How to Create a Pivot Table in VBA

I'm trying to create a Pivot table, but getting Invalid Procedure Call or Argument.

ActiveWorkbook.PivotCaches.Create(SourceType:=xlDatabase, SourceData:="rng", Version:=xlPivotTableVersion14).CreatePivotTable TableDestination:="rngB", TableName:="pvtReportA_B", DefaultVersion:=xlPivotTableVersion14
  • rng (The source) is a range consisting of about 20 columns and a few thousand rows.
  • rngB (The destination) is a single cell in a different worksheet

Can anyone advise where I am going wrong?

EDIT:

My fault, I should have been using rngData and not rng as the Source.

    Set rng = wsA.Range("C14")
    Set rngData = Range(rng, rng.End(xlToRight))
    Set rngData = Range(rng, rng.End(xlDown))
    Set rngB = wsB.Range("C8")

    ActiveWorkbook.PivotCaches.Create(SourceType:=xlDatabase, SourceData:=rngData, Version:=xlPivotTableVersion14).CreatePivotTable TableDestination:=rngB, TableName:="pvtReportA_B", DefaultVersion:=xlPivotTableVersion14

This brings up the PivotTable frame just fine.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

In this instance, I used the wrong range object, which caused Excel to throw a fit.

Set rng = wsA.Range("C14")
Set rngData = Range(rng, rng.End(xlToRight))
Set rngData = Range(rng, rng.End(xlDown))
Set rngB = wsB.Range("C8")

ActiveWorkbook.PivotCaches.Create(SourceType:=xlDatabase, SourceData:=rngData, Version:=xlPivotTableVersion14).CreatePivotTable TableDestination:=rngB, TableName:="pvtReportA_B", DefaultVersion:=xlPivotTableVersion14

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...