从 Excel 调用 VBA 函数 - 在选定 sheet 的选定列中查找

Call VBA function from Excel - Find in a selected column on a selected sheet

正在 Excel VBA 寻求一些专家建议。我编写了一小段代码,用于选择特定 sheet 中的一列并对选择执行 find/search。当我从 Excel 调用该函数时,它没有找到任何内容,因为 find 返回的 Range 值为空。但是,当我 运行 它直接在开发人员 window 中时,它工作正常。

请注意,我知道使用现有的 Excel 宏也可以完成同样的操作。但我不想使用它们是有原因的。希望你明白。

这是代码;

Function MYFIND(x As Range) As Integer
Dim Cell As Range
Worksheets("Sheet4").Select
Columns("A:A").Select
Set Cell = Selection.Find(What:=x.Value, searchDirection:=xlNext, MatchCase:=False)

If Cell Is Nothing Then
    MsgBox "search item " & x.Value & " not found in " & ActiveSheet.Name
Else
    MsgBox "Found item " & Cell.Row
End If
MYFIND = 0 
End Function

可能是什么问题?

杰森,

这个怎么样?

Option Explicit

Function MYFIND(y As String) As Integer

Dim Cell      As Range
Dim GLAccount As Long
Dim x         As Range

Set x = Range(y)

Set Cell = Sheet4.Columns("A:A").Find(What:=x.Value, searchDirection:=xlNext, MatchCase:=False)

If Cell Is Nothing Then
    MsgBox "search item " & x.Value & " not found in " & ActiveSheet.Name
Else
    MsgBox "Found item " & Cell.Row
End If

  MYFIND = Cell.Row()

End Function

呼叫为:

=MyFind("E1")

其中 E1 包含您要查找的值。 我在 Sheet4 的 col A 中设置字母 a-f(使用代码中的代号),它返回 3,因为 c 在第 3 行中。

HTH

尝试使用下面的 UDF,尽量避免使用 Select 和 `Selection.

修改后的 UDF

Function MYFIND(x As Range) As Long

Dim Rng As Range
Dim Cell As Range

' set the range, never use select or selection
Set Rng = Worksheets("Sheet4").Columns("A:A")
Set Cell = Rng.Find(What:=x.Value, LookIn:=xlValues, lookAt:=xlWhole, searchDirection:=xlNext)

If Cell Is Nothing Then
    MYFIND = 0 ' returns 0 if not found
Else
    MYFIND = Cell.Row
End If

End Function

然后,从您的工作表中调用您的 UDF: