美好的一天,
我正在尝试获取创建数据透视表的范围。列数可以每月和行不同。我的代码不在标记部分(粗体)工作以设置数据透视表范围,我相信之后的行不会创建数据透视表缓存。有没有更好的方法来修改或修改此代码?
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"))
答案 0 :(得分:0)
这不需要VBA代码:如果您将数据透视表的源数据转换为Excel表(也称为ListObject),那么您不需要使用VBA来更新数据透视表指向的位置,因为表是动态的范围。因此,当您向表中添加更多数据时,无论何时刷新数据透视表,Excel都知道要包含所有表数据,无论表是增长,缩小还是保持相同的维度。我在以下链接中写了一些关于此的内容:
https://chandoo.org/wp/2014/03/28/tables-pivottables-and-macros-music-to-your-ears/
答案 1 :(得分:0)
感谢@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
答案 2 :(得分:0)
以下两个子程序合并将在B列中找到范围,并在同一张表中添加此范围内的轴。
Public LastRow As Integer
Public LastCol As Integer
Public DataRange As Range
Sub DynamicPivot()
' Inserts pivot table.
' Uses dynamic range variable (DataRange) to build pivot table so the data source can change dimensions every time the pivot is added.
' Rename pivot incase macro wanted for future expansion.
' Note this will work only one time. Close and re-open to re-use.
'This sets the dynamic data range. (See Sub below)
Call PivCacheTrialBalance
Sheets("Analysis").Range("C6").Select
ThisWorkbook.PivotCaches.Add(SourceType:=xlDatabase, SourceData:=DataRange) _
.CreatePivotTable TableDestination:="R4C" & Range("B5") _
.CurrentRegion.Columns.Count + 2
End Sub
Sub PivCacheTrialBalance()
' Pivot table cache range set as a public variable (named DataRange).
Sheets("Analysis").Select
With ActiveSheet
LastRow = .Cells(.Rows.Count, "B").End(xlUp).Row
LastCol = .Cells(5, .Columns.Count).End(xlToLeft).Column
End With
Set DataRange = ActiveSheet.Range(Cells(5, 2), Cells(LastRow, LastCol))
End Sub