简体   繁体   中英

can't find email string using Find method in excel vba

I'm trying to find the address of the cell containing a specific email address. here's my code:

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

EDIT post answer 1

I've taken the suggestion made in answer #1 and changed to code to be:

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

The sub test_email_find_code works great. When I try to use function find_email in a cell, however, it doesn't work. I don't really understand how to research this. Do I have to adjust the range input somehow?

To make it work like you have written you'll need to change the With line like this:

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

Here's your full code located in a separate module:

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

You can test it with another sub like this:

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

Or use an in-cell function like this:

=find_email(A1:D100)

Result depends on the answer, I used cell C4 so the result was $C$4

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM