2013-02-26 67 views
0

我試圖篩選出基於在列值某些單元格,但我擔心的是,第一個篩選器操作污染休息,雖然我試圖通過設置FILTERMODE爲false,以取消設置過濾器。自動篩選工作不正常

我選擇的方法是這樣的:

Function GetRowRange(sheetRange, column, value) As Range 
'check for a valid section column 
sheetRange.AutoFilterMode = False 
sheetRange.UsedRange.AutoFilter Field:=column, Criteria1:=value 
Set GetRowRange = sheetRange.UsedRange.SpecialCells(xlCellTypeVisible) 
MsgBox ("col:" & column & " val: " & value & " rows:" & GetRowRange.Rows.Count) 
sheetRange.AutoFilterMode = False 
End Function 

而且從MSGBOX我可以看到,只有第一個返回任何行

+0

不知何故,這個代碼看起來很熟悉! ;-) – 2013-02-26 09:32:29

+0

@PeterAlbert我想我會創建一個新的線程,而不是利用你的幫助:) – Jakob 2013-02-26 09:33:45

回答

3

這是一個非常討厭的問題! :-)

的問題是,應用自動篩選和.SpecialCells(xlCellTypeVisible)後,新的Range對象是由多個的,合併範圍。

E.g.當過濾此表爲B, enter image description here

您的範圍對象將有3個區域,每個1x2單元。對於一些奇怪的原因,Rows.Count沒有考慮這些方面考慮,所以Selection.Rows.Count是1,雖然它應該是3,但是,如果您遍歷所有的行枚舉,它會按預期工作:

lngCount = 0 
For Each r In Selection.Rows 
    lngCount = lngCount + 1 
Next 

這將返回3.

所以你GetRowRange將返回正確的範圍內,但.Rows.Count程序將提供錯誤的結果。使用此功能來代替:

Function RowCount(rngAreas As Range) As Long 
    Dim lngCount As Long 
    Dim rng As Range 
    For Each rng In rngAreas.Areas 
     lngCount = lngCount + rng.Rows.Count 
    Next 
    RowCount = lngCount 
End Function 

只是一個側面說明:要知道,你的GetRowRange也將隨時返回你的表的第一標題行,所以相應地處理這個!

+0

什麼奇怪的問題,再次 – Jakob 2013-02-26 10:33:34

+0

感謝你作爲一個側面說明,你知道,如果像.CountiF Excel的功能受此 - 我有這個奇怪的錯誤,當我這樣做對一列,場:= 2它工作正常,但是當現場:= 3這是行不通的,而我只得到像2個或3行返回如果我跑.Count如果列 – Jakob 2013-02-26 12:35:02

+0

不知道。 :-(也許嘗試'.Subtotal'替代? – 2013-02-26 12:38:04