Home » excel » vba – why is my visual basic excel code returning #value in my cell

vba – why is my visual basic excel code returning #value in my cell

Posted by: admin May 14, 2020 Leave a comment

Questions:

why is my visual basic excel code returning #value in my cell? I am looking to extract the email address from cell A1. Below is my code

Function ExtractEmailAddress(s As String) As String
    Dim AtSignLocation As Long
    Dim i As Long
    Dim TempStr As String
    Const CharList As String = "[A-Za-Z0-9._-]"

    'Get location of the @
    AtSignLocation = InStr(s, "@")
    If AtSignLocation = 0 Then
        ExtractEmailAddress = "" 'no email address is there
    Else
        TempStr = ""
        'Get 1st half of the email address
        For i = AtSignLocation - 1 To 1 Step -1
            If Mid(s, i, 1) Like CharList Then
                    TempStr = Mid(s, i, 1) & TempStr
            Else
                Exit For
            End If
        Next i
        If TempStr = "" Then Exit Function
        'get 2nd half of the email address
        TempStr = TempStr & "@"
        For i = AtSignLocation + 1 To Len(s)
            If Mid(s, i, 1) Like CharList Then
                TempStr = TempStr & Mid(s, i, 1)
            Else
                Exit For
            End If
        Next i
    End If
    'remove trailing period if there is any
    If Right(TempStr, 1) = "." Then TempStr = _
        Left(TempStr, Len(TempStr) - 1)
    ExtractEmailAddress = TempStr
End Function

I have also included a screen shot of the excel VBA.

ScreenShot:

ScreenShot

Also, here is a screenshot of how its returning the value

Returned value screenshot:

returned value screenshot

How to&Answers:

I get “Invalid pattern string” error here:

If Mid(s, i, 1) Like CharList Then

The problem is with the CharList constant:

Const CharList As String = "[A-Za-Z0-9._-]"

Replace A-Za-Z with A-Za-z and the function starts working =)

Const CharList As String = "[A-Za-z0-9._-]"