遍历整个列以查找值
我如何循环访问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.我的function在input第二个For之前停止。 如果我在Rng.Cells(row,col).Value上添加一个手表,我得到了一个
<Application-defined or object-defined error>
在观察窗口中,但没有popup。
谢谢。
编辑
第二种scheme
使用Rng.Find(Item).Row
Function FindRow(Item As String, Rng As range) As Variant FindRow = Rng.Find(Item).Row End Function
/!\如果Item不在范围内,它将返回#VALUE而不是#N / A
为什么不使用内置的MATCH
function?
=MATCH(C3,A:A,0)
…因为你想一次search很多列。 要做到这一点,你可以使用这个UDF:
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