2016-07-08 878 views
1

我正在嘗試查找工作表中篩選範圍的行數。 LstRow2是我試圖找到的變量。有了這段代碼,我得到了未經過濾的行數。Excel VBA篩選篩選範圍的最後一行

CSht.Range(CSht.Cells(1, 1), CSht.Cells(LstRow1, LstCol1)).AutoFilter Field:=2, Criteria1:="RA" 
     With CSht 
     LstRow2 = .UsedRange.SpecialCells(xlCellTypeLastCell).Row 
     End With 

Here is the data that I am filtering

回答

1

您需要使用僅可見單元格的工作,因爲它的過濾。

試試這個:

With CSht 

    'load filter cells into Range object 
    Dim rngFilter as Range 
    Set rngFilter = Intersect(.UsedRange,.UsedRange.Offset(1)).SpecialCells(xlCellTypeVisible) 

    'find the max number of elements split by $ in the range address 
     'needs to be dynamic because of areas 
    Dim lUpper as Long 
    lUpper = UBound(Split(rngFilter.Address,"$")) 

    'the last element will be the last row in the filtered range 
     'the last number in the rngFilter.Address 
    Dim LstRow2 as Long 
    LstRow2 = Split(rngFilter.Address,"$")(lUpper) 

End With 
+0

嗨,Scott。我意識到LastRow2會出現一個不正確的值。我也不確定最上面是什麼。謝謝你的幫助。 – Liz

+0

@Liz - 'lUpper'是一個變量,用於在用'$'分割公式時捕獲數組中的最高元素。這是必要的,因爲過濾時範圍內的區域數量可以是任意的。最高的元素將始終有最後一行過濾的數據。當你說'LstRow2'出現一個不正確的值時,你是什麼意思? –

+0

我的意思是這個值應該是3,但它是以5的形式出現的,這是過濾列表之前的元素的數量。 – Liz

0

你爲什麼不更換此行

LstRow2 = .UsedRange.SpecialCells(xlCellTypeLastCell).Row 

隨着

LstRow2 = .Cells(.rows.count, 1).end(xlup).row 
+0

並沒有爲我工作。我得到了相同的結果 – Liz

+0

這不會起作用,因爲'.End(xlUp)'會忽略過濾的範圍。它僅作用於整個工作表。 –

+0

剛剛爲我工作。我在第1列做了一堆單個數字並對它們進行了過濾,以便第5行中的某些內容將成爲最後一行,第6-10行被隱藏,並且lastrow最終結束爲5. – Rodger

0

當前區域會爲你做它在一個單一的線

LastRow = sht.Range("A1").CurrentRegion.Rows.Count 
+0

這不適合我。我得到的數字與之前的行數相同 – Liz

+0

是的,我很害怕這個,因爲我希望得到另一個不適合你的結果。你可以分享剩下的代碼嗎? – Rodger

+0

或者你是否可以嘗試一個測試子程序,它對你的數據真的很短,並拿出所有其他可能的影響因素,並查看一個或兩個代碼片段是否適合你? – Rodger