简体   繁体   中英

How do I dynamically select the range of the sheet

The code that works on 2016 version selecting just the sheet name:

ActiveWorkbook.Worksheets("Summary").PivotTables("PivotTable8").PivotCache.Create(SourceType:=xlDatabase,
    SourceData:= _
            "Sheet1!R1C1:R29463CFI", Version:=xlPivotTableVersion15).CreatePivotTable TableDestination:="Sheet2!R3C1", TableName:="PivotTable1", DefaultVersion:=6

In the below code I want the range for sourcedata to be fetched depending on the active cells of the sheet. In Excel 2016 the code works even if the entire sheet is selected but in Excel 2013, only if the range of active cells is provided does the code run.

 ActiveWorkbook.PivotCaches.Create(SourceType:=xlDatabase, SourceData:= _
    "Sheet1!R1C1:R29463C165", Version:=xlPivotTableVersion15).CreatePivotTable _
    TableDestination:="Sheet2!R3C1", TableName:="PivotTable1", DefaultVersion _
    :=xlPivotTableVersion15

code would be like this. My version is 14.

Sub test()
    Dim Ws As Worksheet, toWs As Worksheet
    Dim Wb As Workbook
    Dim pv As PivotTable, pvCache As PivotCache

    Set Wb = ThisWorkbook
    Set Ws = Sheets(1)
    Set toWs = Sheets(2)

        Set pvCache = Wb.PivotCaches.Create(xlDatabase, Ws.Range("a1").CurrentRegion, xlPivotTableVersion14)
        Set pv = pvCache.CreatePivotTable(TableDestination:=toWs.Range("f1"))



End Sub

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