简体   繁体   中英

EXCEL VBA, Multiple consolidation range. Can't Change the refence to sheet from name to index

Here something I cannot figure out.

I am creating a pivot from multiple ranges on a new sheet.

This works:

arr = Array(Array("US!R6C2:R17C23", "US"), Array("Japan!R6C2:R17C23", "Japan"), Array( _
    "Other1!R6C2:R17C23", "Other1"), Array("Other2!R6C2:R17C23", "Other2"), Array( _
    "EU!R6C2:R17C23", "EU"))
ActiveWorkbook.PivotCaches.Create(SourceType:=xlConsolidation, SourceData:=arr, Version:=6).CreatePivotTable TableDestination:= _
    "", TableName:="PivotTable9", _
    DefaultVersion:=6

This does not work:

arr = Array(Array(Worksheets(2).Range("B6:W17"), "US"), Array("Japan!R6C2:R17C23", "Japan"), Array( _
    "Other1!R6C2:R17C23", "Other1"), Array("Other2!R6C2:R17C23", "Other2"), Array( _
    "EU!R6C2:R17C23", "EU"))ere
ActiveWorkbook.PivotCaches.Create(SourceType:=xlConsolidation, SourceData:=arr, Version:=6).CreatePivotTable TableDestination:= _
    "", TableName:="PivotTable9", _
    DefaultVersion:=6

The difference is in how I try to reference the first part:

Array(Worksheets(2).Range("B6:W17"), "US"))

vs

Array("US!R6C2:R17C23", "US")

Any help to understand why I can't make this change and what I need to do instead would be great.

Try changing the:

Array(Worksheets(2).Range("B6:W17"), "US"))

To:

Array(Chr(34) &Worksheets(2).Name &"!" & Worksheets(2).Range("B6:W17").Address(ReferenceStyle:=xlR1C1) & Chr(34), "US")

I'd steer clear of using the Consolidation method to create PivotTables...it has quite a few limitations, and at the same time better alternatives exist, including:

  1. Using VBA to mash all your data from seperate tables into one table. See https://stackoverflow.com/a/47279374/2507160
  2. Using PowerQuery to do the same. See https://stackoverflow.com/a/47170312/2507160

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