无法在excel vba中使用Find方法查找电子邮件字符串

时间:2014-10-12 01:54:16

标签: excel vba excel-vba

我正在尝试查找包含特定电子邮件地址的单元格的地址。这是我的代码:

Function find_email(range_input As Range) As String

    Dim item_input As String
    item_input = "test@test.com"

    Dim found_range As Range

    With Worksheets("test_sheet").range_input

        Set found_range = .Find(What:=item_input, LookIn:=xlValues, LookAt:=xlPart)

    End With
    find_email = found_range.Address

End Function

编辑回复1

我已经采纳了在答案#1中提出的建议,并将其更改为代码:

Public Function find_email(range_input As Range, string_input As String, collumn_offsett As Integer) As String

    Dim found_range As Range

    With Worksheets("test_sheet").Range(range_input.Address)
        Set found_range = .Find(What:=string_input, LookIn:=xlValues, LookAt:=xlPart)
    End With

    Dim output_range As Range
    Set output_range = found_range.Offset(0, collumn_offsett)
    find_email = output_range

End Function

Sub test_email_find_code()
    Debug.Print find_email(Range("f1:f7"), "test@test.com", -3)
End Sub

test_email_find_code效果很好。但是,当我尝试在单元格中使用函数find_email时,它不起作用。我真的不明白如何研究这个。我是否必须以某种方式调整范围输入?

1 个答案:

答案 0 :(得分:1)

为了让它像你写的那样工作,你需要像这样改变With行:

With Worksheets("test_sheet").Range(range_input.Address)

以下是您的完整代码位于单独的模块中:

Public Function find_email(range_input As Range) As String
    Dim item_input As String
    item_input = "test@test.com"

    Dim found_range As Range

    With Worksheets("test_sheet").Range(range_input.Address)
        Set found_range = .Find(What:=item_input, LookIn:=xlValues, LookAt:=xlPart)
    End With
    find_email = found_range.Address
End Function

您可以使用其他子类进行测试:

Sub findEmail()
    Debug.Print find_email(Range("A1:D100"))
End Sub

或使用像这样的内嵌函数:

=find_email(A1:D100)

结果取决于答案,我使用了单元格C4,结果是$C$4