vba check email format

Function IsValidEmail(email As String) As Boolean
Dim regex As Object
Dim pattern As String
Dim parts() As String
Dim domainPart As String

' Initialize the regex object
Set regex = CreateObject("VBScript.RegExp")

' Define the email pattern, updated to prevent consecutive dots after the @ symbol
pattern = "^[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,}$"

' Set regex properties
With regex
    .Global = True
    .IgnoreCase = True
    .Pattern = pattern
End With

' Check if the email matches the pattern
If regex.Test(email) Then
    ' Split the email into local and domain parts
    parts = Split(email, "@")

    ' Ensure there are exactly two parts (local and domain)
    If UBound(parts) = 1 Then
        domainPart = parts(1)

        ' Check for consecutive dots in the domain part
        If InStr(domainPart, "..") > 0 Then
            IsValidEmail = False
        Else
            IsValidEmail = True
        End If
    Else
        IsValidEmail = False
    End If
Else
    IsValidEmail = False
End If

' Clean up
Set regex = Nothing

End Function

Function ValidateMultipleEmails(emails As String) As Boolean
Dim emailArray() As String
Dim i As Integer

' Split the emails string into an array using ";" as delimiter
emailArray = Split(emails, ";")

' Loop through each email in the array and validate it
For i = LBound(emailArray) To UBound(emailArray)
    If Not IsValidEmail(Trim(emailArray(i))) Then
        ValidateMultipleEmails = False
        Exit Function
    End If
Next i

ValidateMultipleEmails = True

End Function

Comments

No comments yet. Why don’t you start the discussion?

Leave a Reply

Your email address will not be published. Required fields are marked *