【问题标题】:Excel VBA Pivot table Dynamic RangeExcel VBA 数据透视表动态范围
【发布时间】:2018-02-16 13:02:28
【问题描述】:

早安,

我正在尝试获取创建数据透视表的范围。每个月和行的列金额可能不同。我的代码在标记部分(粗体)无法设置数据透视表范围,我相信之后的行也不会创建数据透视缓存。请问有没有更好的方法或修复此代码?

Dim RowsCount As Long, ColCount As Long
Dim wsStores As Worksheet
Dim pCache As PivotCache
Dim pTable As PivotTable
Dim PvtRange As Range
Dim lastRows As Long

Set wsStores = Worksheets.Add
RowsCount = Worksheets("Active Instances").Cells(14, 1).End(xlDown).Row
ColCount = Worksheets("Active Instances").Cells(14, Columns.Count).End(xlToLeft).Column
**PvtRange = Worksheets("Active Instances").Range(RowsCount, ColCount)**
Set pCache = ActiveWorkbook.PivotCaches.Create(xlDatabase, PvtRange)
Set pTable = pCache.CreatePivotTable(wsStores.Range("A3"))

【问题讨论】:

  • PvtRange 是一个 Range 对象。您需要在其前面加上“Set”一词,如下所示:Set PvtRange = Worksheets("Active Instances").Range(RowsCount, ColCount)。但即便如此,这段代码也不起作用,因为它只是将范围设置为单个单元格,并且您不能从单个单元格中创建数据透视表。

标签: excel dynamic range pivot-table vba


【解决方案1】:

感谢@jeffreyweir 的回复 我设法用以下代码修复它:

Dim wsStores As Worksheet
Dim pCache As PivotCache
Dim pTable As PivotTable
Dim lastRows As Long

Set wsStores = Worksheets.Add
Set pCache = ActiveWorkbook.PivotCaches.Create(xlDatabase, Sheets("Active Instances").Range("A14").CurrentRegion.Address(ReferenceStyle:=xlR1C1))
Set pTable = pCache.CreatePivotTable(wsStores.Range("A3"))

我不想从数据透视表更改为 ListObject,因为其余代码(很好,但没有添加到问题中)已经设置好,没有任何问题。以后我一定会尝试使用ListObject

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-05-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-05-30
    • 1970-01-01
    • 2019-06-16
    相关资源
    最近更新 更多