Function Returning Wrong Result

Ark68

Well-known Member
Joined
Mar 23, 2004
Messages
4,564
Office Version
  1. 365
  2. 2016
Platform
  1. Windows
I found this webpage providing me with a Function to check email address validity. (Validate Email Address - VBA Code - Excel)

I made some adjustments in order to check the two different available patterns, but even when I put in a valid email address (xaxaxaxaxa@gmail.com), the result is always false. I'm wondering if someone could advise what part of my code is contributing to the wrong answer.

Code:
Function IsValidEmail(sEmailAddress As String) As Boolean
    'Code from Officetricks (https://officetricks.com/validate-email-address-vba-code-excel/)
    'Define variables
    'Stop
    Dim sEmailPattern As String
    Dim oRegEx As Object
    Dim bReturn As Boolean
   
    'Use the below regular expressions
    sEmailPattern1 = "^\w+([\.-]?\w+)*@\w+([\.-]?\w+)*(\.\w{2,3})+$" 'or
    sEmailPattern2 = "^([a-zA-Z0-9_\-\.]+)@[a-z0-9-]+(\.[a-z0-9-]+)*(\.[a-z]{2,3})$"
   
    'Create Regular Expression Object
    Set oRegEx = CreateObject("VBScript.RegExp")
    oRegEx.Global = True
    oRegEx.IgnoreCase = True
    oRegEx.Pattern = sEmailPattern
    bReturn = False
   
    'Check if Email match regex pattern
    If oRegEx.Test(sEmailAddress1) Or oRegEx.Test(sEmailAddress2) Then
        'Debug.Print "Valid Email ('" & sEmailAddress & "')"
        bReturn = True
    Else
        'Debug.Print "Invalid Email('" & sEmailAddress & "')"
        bReturn = False
    End If

    'Return validation result
    IsValidEmail = bReturn
End Function
 

Excel Facts

Waterfall charts in Excel?
Office 365 customers have access to Waterfall charts since late 2016. They were added to Excel 2019.
You've made changes to the core of the function.
EDIT:
This part is causing the problems
If oRegEx.Test(sEmailAddress1) Or oRegEx.Test(sEmailAddress2) Then
Undo those changes and call the function as intended:

VBA Code:
    If IsValidEmail("xaxa@gmail.com") Or IsValidEmail("someone@web.com") Then
 
Upvote 0
You haven't supplied a pattern for your regex.
 
Upvote 0
Hi GWteb ... this function has two different patterns of email addresses for which the user's entry can be checked with. That was what I was checking for, if the one email address submitted matches either one of the two patterns, not to check two different addresses.

But, yes ... that line is wrong, there is only 1 email address (sEmailAddress). It is this single email address that needs to be checked against the two patterns for validity. (sEmailPattern1, sEmailPattern2), so that is what I need to fix.

Thanks!
 
Upvote 0
Simply comment out one of the patterns
VBA Code:
'    sEmailPattern1 = "^\w+([\.-]?\w+)*@\w+([\.-]?\w+)*(\.\w{2,3})+$" 'or
    sEmailPattern2 = "^([a-zA-Z0-9_\-\.]+)@[a-z0-9-]+(\.[a-z0-9-]+)*(\.[a-z]{2,3})$"
 
Upvote 0
This is returning the same ...
Rich (BB code):
Function IsValidEmail(sEmailAddress As String) As Boolean
    'Code from Officetricks
    'Define variables
    'Stop
    Dim sEmailPattern As String
    Dim oRegEx As Object
    Dim bReturn As Boolean
 
    'Use the below regular expressions
    sEmailPattern1 = "^\w+([\.-]?\w+)*@\w+([\.-]?\w+)*(\.\w{2,3})+$" 'or
    sEmailPattern2 = "^([a-zA-Z0-9_\-\.]+)@[a-z0-9-]+(\.[a-z0-9-]+)*(\.[a-z]{2,3})$"
 
    'Create Regular Expression Object
    Set oRegEx = CreateObject("VBScript.RegExp")
    oRegEx.Global = True
    oRegEx.IgnoreCase = True
    oRegEx.Pattern = sEmailPattern1
    bReturn = False
 
    'Check if Email match regex pattern
    'first pattern
    If oRegEx.Test(sEmailAddress) Then
        'Debug.Print "Valid Email ('" & sEmailAddress & "')"
        bReturn = True
    Else
        'Debug.Print "Invalid Email('" & sEmailAddress & "')"
        bReturn = False
    End If
 
    'second pattern
    oRegEx.Pattern = sEmailPattern2
    If oRegEx.Test(sEmailAddress) Then
        'Debug.Print "Valid Email ('" & sEmailAddress & "')"
        bReturn = True
    Else
        'Debug.Print "Invalid Email('" & sEmailAddress & "')"
        bReturn = False
    End If

    'Return validation result
    IsValidEmail = bReturn
End Function
 
Last edited:
Upvote 0
Actually .... changed it to:

Rich (BB code):
Function IsValidEmail(sEmailAddress As String) As Boolean
    'Code from Officetricks
    'Define variables
    'Stop
    Dim sEmailPattern As String
    Dim oRegEx As Object
    Dim bReturn As Boolean
   
    'Use the below regular expressions
    sEmailPattern1 = "^\w+([\.-]?\w+)*@\w+([\.-]?\w+)*(\.\w{2,3})+$" 'or
    sEmailPattern2 = "^([a-zA-Z0-9_\-\.]+)@[a-z0-9-]+(\.[a-z0-9-]+)*(\.[a-z]{2,3})$"
   
    'Create Regular Expression Object
    Set oRegEx = CreateObject("VBScript.RegExp")
    oRegEx.Global = True
    oRegEx.IgnoreCase = True
    oRegEx.Pattern = sEmailPattern1
    bReturn = False
   
    'Check if Email match regex pattern
    If oRegEx.Test(sEmailAddress) Then
        'Debug.Print "Valid Email ('" & sEmailAddress & "')"
        bReturn = True
        IsValidEmail = bReturn
    Else
        'Debug.Print "Invalid Email('" & sEmailAddress & "')"
        bReturn = False
        IsValidEmail = bReturn
    End If
   
    If bReturn = False Then
        'second pattern
        oRegEx.Pattern = sEmailPattern2
        If oRegEx.Test(sEmailAddress) Then
            'Debug.Print "Valid Email ('" & sEmailAddress & "')"
            bReturn = True
            IsValidEmail = bReturn
        Else
            'Debug.Print "Invalid Email('" & sEmailAddress & "')"
            bReturn = False
            IsValidEmail = bReturn
        End If
    End If

    'Return validation result
    IsValidEmail = bReturn
End Function
 
Upvote 0
I made some adjustments in order to check the two different available patterns

First, put Option Explicit at the top of the VBA module. You will discover that you fail to declare (with Dim or ReDim) some variables.

That will highlight some mistakes, namely references to uninitialized variables sEmailAddress1 and sEmailAddress2.

I suspect you meant to type sEmailPattern1 and sEmailPattern2.

But based on the original design, those should not be the parameters for oRegEx.Test.

Instead, you should use oRegEx.Test(sEmailAddress), referring to the function parameter.

Second, you create two patterns, but you set oRegEx.Pattern to only one (sEmailPattern). And in fact, you do not set sEmailPattern at all(!).

Finally, the statement If oRegEx.Test(...) Or oRegEx.Test(...) is inefficient. In VBA, both regular expressions are evaluated, even if the first is true, unlike the left-to-right evaluation in Excel.

In sum, your implementation should be the following.

(Note: I am not sure what the difference between the two patterns is. I am not familiar with the syntax of VBScript regular expressions. In fact, it might be wrong to try both patterns. The difference might depend on the version of VBScript that you use. A VBScript expert will need to comment.)

Code:
Option Explicit

Function IsValidEmail(sEmailAddress As String) As Boolean
    'Code from Officetricks (https://officetricks.com/validate-email-address-vba-code-excel/)
    'Define variables
    'Stop
    Dim sEmailPattern1 As String
    Dim sEmailPattern2 As String
    Dim oRegEx As Object
    Dim bReturn As Boolean
  
    'Use the below regular expressions
    sEmailPattern1 = "^\w+([\.-]?\w+)*@\w+([\.-]?\w+)*(\.\w{2,3})+$" 'or
    sEmailPattern2 = "^([a-zA-Z0-9_\-\.]+)@[a-z0-9-]+(\.[a-z0-9-]+)*(\.[a-z]{2,3})$"
  
    'Create Regular Expression Object
    Set oRegEx = CreateObject("VBScript.RegExp")
    oRegEx.Global = True
    oRegEx.IgnoreCase = True
    oRegEx.Pattern = sEmailPattern1
      
    'Check if Email match regex pattern1
    If oRegEx.Test(sEmailAddress) Then
        'Debug.Print "Valid Email pattern1 ('" & sEmailAddress & "')"
        bReturn = True
    Else
        'Debug.Print "Invalid Email pattern1 ('" & sEmailAddress & "')"
        bReturn = False
    End If
   
    'Check if Email match regex pattern2
    If Not bReturn Then
        oRegEx.Pattern = sEmailPattern2
        If oRegEx.Test(sEmailAddress) Then
            'Debug.Print "Valid Email pattern2 ('" & sEmailAddress & "')"
            bReturn = True
        'Else
            'Debug.Print "Invalid Email pattern2 ('" & sEmailAddress & "')"
        End If
    End If

    'Return validation result
    IsValidEmail = bReturn
End Function

Uncomment the Debug.Print and Else statements for debugging purposes. Better, use f9 to set breakpoints and/or f8 to step through the execution.
 
Upvote 0
My changes in post #8 is assessing the email address (sEmailAddress) effectively and returning the right value for bReturn. (bReturn is declared publically as Boolean)
Something is happening with the value of bReturn after leaving the function.
When stepping through the code, the code is triggered true on the first pattern. At the end of the code bReturn = TRUE.
But the result of Msgbox bReturn in my routine that called the function returns FALSE.

Code:
If Target.Address = "$K$12" Then 'email
            sEmailAddress = .Range("K12").Value
            IsValidEmail (sEmailAddress)
            MsgBox bReturn
        End If
 
Upvote 0

Forum statistics

Threads
1,214,635
Messages
6,120,660
Members
448,975
Latest member
sweeberry

We've detected that you are using an adblocker.

We have a great community of people providing Excel help here, but the hosting costs are enormous. You can help keep this site running by allowing ads on MrExcel.com.
Allow Ads at MrExcel

Which adblocker are you using?

Disable AdBlock

Follow these easy steps to disable AdBlock

1)Click on the icon in the browser’s toolbar.
2)Click on the icon in the browser’s toolbar.
2)Click on the "Pause on this site" option.
Go back

Disable AdBlock Plus

Follow these easy steps to disable AdBlock Plus

1)Click on the icon in the browser’s toolbar.
2)Click on the toggle to disable it for "mrexcel.com".
Go back

Disable uBlock Origin

Follow these easy steps to disable uBlock Origin

1)Click on the icon in the browser’s toolbar.
2)Click on the "Power" button.
3)Click on the "Refresh" button.
Go back

Disable uBlock

Follow these easy steps to disable uBlock

1)Click on the icon in the browser’s toolbar.
2)Click on the "Power" button.
3)Click on the "Refresh" button.
Go back
Back
Top