简体   繁体   中英

Excel VBA Pivot Table data source issue

I have the following code...

    ActiveWorkbook.PivotCaches.Create(SourceType:=xlDatabase, SourceData:= _
    "page!R2C1:R1981C43", Version:=xlPivotTableVersion15).CreatePivotTable _
    TableDestination:="", TableName:="PivotTable5", DefaultVersion _
    :=xlPivotTableVersion15

How would i change it from "page" to pull for any current worksheet name that I want to attempt.

For example if I run this on a worksheet named "pages" it gives me an error, how would I change it to accept any worksheet name?

Just declare a variable and use that:

Dim myWorksheet as Worksheet
Set myWorksheet = Activesheet

ActiveWorkbook.PivotCaches.Create(SourceType:=xlDatabase, SourceData:= _
    myWorksheet & "!R2C1:R1981C43", Version:=xlPivotTableVersion15).CreatePivotTable _
    TableDestination:="", TableName:="PivotTable5", DefaultVersion _
    :=xlPivotTableVersion15

This is untested, but I'm pretty sure that should work.

Dim wbpage as worksheet

set wbpage = thisworkbook.sheets(1) 'or whatever

ActiveWorkbook.PivotCaches.Create(SourceType:=xlDatabase, SourceData:= _
    wbpage.name & "!R2C1:R1981C43", Version:=xlPivotTableVersion15).CreatePivotTable _
    TableDestination:="", TableName:="PivotTable5", DefaultVersion _
    :=xlPivotTableVersion15

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM