遍历整个列以查找值

时间:2015-03-25 10:34:10

标签: excel vba

如何在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.我的函数在输入第二个For之前停止。如果我在Rng.Cells(row,col).Value上添加一个手表,我得到了一个

<Application-defined or object-defined error> 

在观察窗口中,但没有弹出窗口。

谢谢。

修改

第二个解决方案

使用Rng.Find(Item).Row

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

FindRow = Rng.Find(Item).Row

End Function

/!\如果项目不在范围内,则返回#VALUE而不是#N / A

1 个答案:

答案 0 :(得分:3)

为什么不使用内置的MATCH函数?

=MATCH(C3,A:A,0)

enter image description here


...因为您想一次搜索多个列。为此,您可以使用此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

enter image description here