【发布时间】: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