Vba 更新数据透视范围字符串或范围
我正在编写一个我拼凑在一起的代码,但我发现在找到“已使用”范围后(由于可靠性原因,我尝试不使用Vba 更新数据透视范围字符串或范围,vba,excel,Vba,Excel,我正在编写一个我拼凑在一起的代码,但我发现在找到“已使用”范围后(由于可靠性原因,我尝试不使用.usedrange),即SourceData:=需要一个字符串(我想) 是否有一种方法可以通过从数据工作表到透视表数据范围的范围?我试着添加RealUsedRange.Address,但也没有成功 Sub UpdatePivotRange() Dim Rng1 As Range Dim oWB As Workbook Dim oWS
.usedrange
),即SourceData:=
需要一个字符串(我想)
是否有一种方法可以通过从数据
工作表到透视表数据范围的范围?我试着添加RealUsedRange.Address
,但也没有成功
Sub UpdatePivotRange()
Dim Rng1 As Range
Dim oWB As Workbook
Dim oWS As Worksheet
Dim DataSheet As Worksheet
Dim oPT As PivotTable
Set oWB = ThisWorkbook
Set DataSheet = oWB.Sheets("Data")
Set Rng1 = RealUsedRange
If Rng1 Is Nothing Then
MsgBox "There is no used range, the worksheet is empty."
Else
For Each oWS In oWB.Worksheets
For Each oPT In oWS.PivotTables
'ERRROR BEGINS HERE #####
oPT.ChangePivotCache _
oWB.PivotCaches.Create(SourceType:=xlDatabase, SourceData:=Rng1)
'ERROR ENDS HERE #####
Next oPT
Next oWS
End If
End Sub
Public Function RealUsedRange() As Range
Dim FirstRow As Long
Dim LastRow As Long
Dim FirstColumn As Integer
Dim LastColumn As Integer
Dim DataSheet As Worksheet
Dim oWB As Workbook
On Error Resume Next
Set oWB = ThisWorkbook
Set DataSheet = oWB.Sheets("Data")
With DataSheet
FirstRow = DataSheet.Cells.Find(What:="*", After:=Cells(1, 1), LookIn:=xlValues, LookAt:= _
xlPart, SearchOrder:=xlByRows, SearchDirection:=xlNext).Row
FirstColumn = DataSheet.Cells.Find(What:="*", After:=Cells(1, 1), LookIn:=xlValues, LookAt:= _
xlPart, SearchOrder:=xlByColumns, SearchDirection:=xlNext).Column
LastRow = DataSheet.Cells(.Rows.Count, "A").End(xlUp).Row
LastColumn = DataSheet.Cells(1, Columns.Count).End(xlToLeft).Column
Set RealUsedRange = Range(Cells(FirstRow, FirstColumn), Cells(LastRow, LastColumn))
End With
MsgBox "The range is" & RealUsedRange.Address
On Error GoTo 0
End Function
我可以通过添加以下内容来修改出错的行:
oPT.ChangePivotCache _
oWB.PivotCaches.Create(SourceType:=xlDatabase, SourceData:="Data!" & Rng1.Address(ReferenceStyle:=xlR1C1))
希望这有助于任何人展望未来