重复读取过滤的表单时,范围保持不变
问题描述:
我有一个包含多个类别的工作表和一个包含数据透视表的工作表。重复读取过滤的表单时,范围保持不变
我按类别过滤,创建新工作簿,将数据透视表工作表和过滤类别复制到新工作簿。我重复每个类别的过程。
我的问题是第一类范围是正确的,但是当我重新查询其他类别的范围时,范围保持不变。
For i = 1 To 10 '10 categories
...
Set Data_sht = NewBook.Worksheets("Temp")
Set Pivot_sht = NewBook.Worksheets("Category")
PivotName = "PivotTable2"
Set StartPoint = Data_sht.Range("A1")
Set DataRange = Data_sht.Range(StartPoint, StartPoint.SpecialCells(xlLastCell))
NewRange = Data_sht.Name & "!" & DataRange.Address(ReferenceStyle:=xlR1C1)
'Change Pivot Table Data Source Range Address
Pivot_sht.PivotTables(PivotName).ChangePivotCache NewBook.PivotCaches.Create(SourceType:=xlDatabase, SourceData:=NewRange)
....
Next i
第一遍(类别)的NewRange有545行。我已经证实这是正确的。第二遍(类别)的NewRange仍然包含545行,即使它应该是260行。
有没有办法强制重新读取Data_sht(数据表)?
谢谢。
答
我发现了一些奇怪的东西,但它解决了我的问题。
NewRange = "Temp!A1:X" & LastRow(ActiveSheet)
Function LastRow(sh As Worksheet)
'Excel doesn't seem to return the true count until the WS
'is queried a second time. Bug?
For i = 0 To 2
On Error Resume Next
LastRow = sh.Cells.Find(What:="*", _
After:=sh.Range("A1"), _
Lookat:=xlPart, _
LookIn:=xlValues, _
SearchOrder:=xlByRows, _
SearchDirection:=xlPrevious, _
MatchCase:=False).Row
On Error GoTo 0
Next i
End Function
希望这可以帮助别人。
*我正在按类别过滤* - 我在代码中看不到这一点。但是,如果你真的在你的范围内使用'AutoFilter'方法。看看'SpecialCells(xlCellTypeVisible)'我认为这将帮助你得到你需要的东西。 –
怎么办? Set DataRange = Data_sht.Range(“A1”)。CurrentRegion.SpecialCells(xlCellTypeVisible) – sktneer
SpecialCells(xlLastCell)是使用范围中的最后一个单元格,而不是具有值的最后一个单元格 – Slai