首页 > 解决方案 > 在自定义函数中使用 findnext 不起作用

问题描述

我写了一个自定义的公共函数调用 myLookUp 有 2 个变量,在这个函数中,我使用了 find 和 findnext 函数。我通过在另一个子过程中调用这个自定义函数进行了测试,我给了我正确的结果。但是当我在 Excel 单元格中实际使用此函数时,它返回了#value。我试图调试这段代码。当运行到 Do 循环行时,Set resultFind 什么都不返回?

但是当我在 Sub test() 中进行测试时,Set resultFind 返回“HR00004”

谁能告诉我我的代码有什么问题?

Sub test()

Dim k As Variant
k = myLookUp("HR00004", "Meals")
Debug.Print k

End Sub

Function myLookUp(EmployeeID As String, colName As String) As Variant
'find the range contain EmployeeID
Dim resultFind As Range
Dim lastRow As Long
Dim rangedFind As Range
Dim firstFindRow As Variant
Dim n As Long
Dim colRange As Range

lastRow = shLogs.Range("B" & Rows.Count).End(xlUp).Row
Set rangedFind = shLogs.Range("B8:B" & lastRow)
Set rangedFind = Range("B8:B29")
Set resultFind = rangedFind.Find(EmployeeID, , xlValues, xlWhole, xlByRows, xlNext, False)

If Not resultFind Is Nothing Then
    firstFindRow = resultFind.Row
    n = 0
    'perform next find
    Do
        Set resultFind = rangedFind.FindNext(resultFind)
        If resultFind.Row = firstFindRow Then
            Exit Do
        End If
        n = n + 1
    Loop While resultFind.Row <> firstFindRow
End If
Set colRange = shLogs.Range("D" & firstFindRow & ":D" & firstFindRow + n)
'find the latest result of the column
Set resultFind = colRange.Find(colName, , xlValues, xlPart, , xlNext, False)
myLookUp = shLogs.Range("F" & resultFind.Row).value
End Function

标签: excelvba

解决方案


推荐阅读