2015-03-25 46 views
0

如何遍歷VBA中列的所有行?遍歷整個列以找到值

這是我的樣品:

Function FindRow(Item As String, Rng As range) As Variant 

Dim row As Integer 
Dim col As Integer 

For col = 1 To Rng.Columns.Count 
    For row = 1 To Rng.Rows.Count   
     If Rng.Cells(row, col).Value = Item Then 
      FindRow = row + Rng.row - 1 
      Exit Function 
     End If 
    Next row 
Next col 

FindRow = CVErr(XlCVError.xlErrNA) 

End Function 

如果我的範圍是單個列,Rng.Columns.Count是1和Rng.Rows.Count是進入第二對於前1048576 My功能停止。如果我加上Rng.Cells手錶(行,列).value的,我得到了一個

<Application-defined or object-defined error> 
在監視窗口

,但沒有彈出。

謝謝。

編輯

解決方法二

使用Rng.Find(項目).Row

Function FindRow(Item As String, Rng As range) As Variant 

FindRow = Rng.Find(Item).Row 

End Function 

/!\它返回,而不是#N/A#VALUE如果項目不在範圍內

+1

你爲什麼要通過上百萬行的循環:要做到這一點,你可以使用這個UDF? – 2015-03-25 10:38:13

+0

...或「MATCH」? – 2015-03-25 10:38:40

+0

但是,如果你想循環,也許設置i = 1,並使用「做直到我> Rng.Columns.Count」,並在最後我=我+ 1 – 2015-03-25 10:42:31

回答

3

爲什麼不只是使用內置的MATCH好玩ction?

=MATCH(C3,A:A,0) 

enter image description here


...因爲你想一次搜索到很多列。當你可以使用`Range.Find()`

Function FindRow(lookFor As String, rng As Range) 
    Dim v As Variant 
    Dim iRow As Long 
    Dim iCol As Long 

    'Read contents of range into a Variant array 
    v = rng.Value 

    'Loop through contents to locate the desired element 
    For iRow = LBound(v, 1) To UBound(v, 1) 
     For iCol = LBound(v, 2) To UBound(v, 2) 
      If v(iRow, iCol) = lookFor Then 
       FindRow = iRow 
       Exit Function 
      End If 
     Next iCol 
    Next iRow 



    FindRow = CVErr(XlCVError.xlErrNA) 
End Function 

enter image description here

+0

+1我會這樣做,但是對於OP來說,以供將來參考,當循環遍歷工作表中的所有行時,最好將變量類型聲明爲Long而不是Integer,因爲Integer數據類型只能存儲值爲32768. – Dave 2015-03-25 10:45:45

+0

我需要遍歷未知數量的列和行 – Sara 2015-03-25 10:48:54

+0

@Dave完全迂腐我知道,但一個整數可以容納32,767在VBA – 2015-03-25 11:09:10