主要通过正则表达式来提取字符串中的电子邮件,代码如下:
'---------------------------------------------------------------------------------------
' Procedure : ExtractEmailAddresses
' Author : Daniel Pineault, CARDA Consultants Inc.
' Website : http://www.cardaconsultants.com
' Purpose : Extract e-mail addresses from a supplied string
' Notes : None
' Copyright : The following is release as Attribution-ShareAlike 4.0 International
' (CC BY-SA 4.0) - https://creativecommons.org/licenses/by-sa/4.0/
' Req'd Refs: Uses Late Binding, so none required
'
' Input Variables:
' ~~~~~~~~~~~~~~~~
' sInput : String to parse/extract e-mail addresses from
'
' Usage:
' ~~~~~~
' See TestMe Sub
'
' Revision History:
' Rev Date(yyyy/mm/dd) Description
' **************************************************************************************
' 1 2020-05-13 Initial Release, Forum Help
' 2 2020-05-17 Added a more advanced pattern
'---------------------------------------------------------------------------------------
Public Function ExtractEmailAddresses(ByVal sInput As Variant) As Variant
On Error GoTo Error_Handler
Dim oregEx As Object
Dim oMatches As Object
Dim oMatch As Object
Dim sEmail As String
If Not IsNull(sInput) Then
Set oregEx = CreateObject("vbscript.regexp")
With oregEx
'Basic pattern
'.Pattern = "([a-zA-Z0-9._-]+@[a-zA-Z0-9._-]+\.[a-zA-Z0-9_-]+)"
'More advanced pattern that allow accented characters
.Pattern = "([a-zA-ZF0-9\u00C0-\u017F._-]+@[a-zA-Z0-9\u00C0-\u017F._-]+\.[a-zA-Z0-9\u00C0-\u017F_-]+)"
.Global = True
.IgnoreCase = True
.MultiLine = True
Set oMatches = .Execute(sInput)
End With
For Each oMatch In oMatches
sEmail = oMatch.Value & "," & sEmail
Next oMatch
If Right(sEmail, 1) = "," Then sEmail = Left(sEmail, Len(sEmail) - 1)
ExtractEmailAddresses = Split(sEmail, ",") 'Return an array of email addresses extracted from sInput
Else
ExtractEmailAddresses = Null
End If
Error_Handler_Exit:
On Error Resume Next
If Not oMatch Is Nothing Then Set oMatch = Nothing
If Not oMatches Is Nothing Then Set oMatches = Nothing
If Not oregEx Is Nothing Then Set oregEx = Nothing
Exit Function
Error_Handler:
MsgBox "The following error has occured" & vbCrLf & vbCrLf & _
"Error Number: " & Err.Number & vbCrLf & _
"Error Source: ExtractEmailAddresses" & vbCrLf & _
"Error Description: " & Err.Description & _
Switch(Erl = 0, "", Erl <> 0, vbCrLf & "Line No: " & Erl) _
, vbOKOnly + vbCritical, "An Error has Occured!"
Resume Error_Handler_Exit
End Function
附 件:
点击下载此附件
图 示: