2017-06-13 50 views
0

我不太習慣在VBA中編程。我的目標是製作一個腳本,我可以將它傳遞給我的鏈接,因爲它們的Excel文件長,包含多個單詞(包括一個電子郵件地址)。例如:公司用戶[email protected]VBA驗證列是否包含電子郵件

我堅持使用我的正則表達式傳遞所有數據,並且似乎無法使其濾除任何內容。

Function isEmail(ByVal data As String) 

Dim mailReg As Object 
Set mailReg = CreateObject("VBScript.RegExp") 

Dim regpattern As String 
regpattern = "^[_a-z0-9-]+(.[a-z0-9-]+)@[a-z0-9-]+(.[a-z0-9-]+)*(.[a-z]{2,4})$" 'Expression ok 

Dim arr1() As String 
Dim element As Variant 
Dim strInput As String 

arr1() = Split(data, " ") 

For Each element In arr1 

    If regpattern <> "" Then 
    strInput = element 

    With mailReg 
     .Global = True 
     .MultiLine = True 
     .IgnoreCase = False 
     .Pattern = regpattern 
    End With 

MsgBox (strInput) 

End If 
Next element 
End Function 

我也曾嘗試使用

For Each element In arr1 

If element Like regpattern Then 
MsgBox (element) 

End If 
Next element 
End Function 

但隨後沒有出現在MSGBOX ..

+0

爲什麼'如果regpattern <> 「」 Then' - 是不是應該是'如果元素<> 「」'Then' –

+0

此代碼是一個混亂。正則表達式不正確。你想做什麼?用字符串中的每個電子郵件顯示一條消息?然後使用'Sub',而不是'Function'。 –

+0

電子郵件地址可以包含非字母數字字符,例如「!!#和$。」來源:[Wikipedia](https://en.wikipedia.org/wiki/Email_address)。 –

回答

0
Option Explicit 

Const MODULE_NAME As String = "modMail" 

    '' Validate email address 
    Public Function ValidateEmailAddress(ByVal strEmailAddress As String) As Boolean 
     On Error GoTo Catch 

     Dim objRegExp As New RegExp 
     Dim blnIsValidEmail As Boolean 

     objRegExp.IgnoreCase = True 
     objRegExp.Global = True 
     objRegExp.Pattern = "^([a-zA-Z0-9_\-\.]+)@[a-z0-9-]+(\.[a-z0-9-]+)*(\.[a-z]{2,3})$" 

     blnIsValidEmail = objRegExp.Test(strEmailAddress) 
     ValidateEmailAddress = blnIsValidEmail 

     Exit Function 

    Catch: 
     ValidateEmailAddress = False 
     MsgBox "Module: " & MODULE_NAME & " - ValidateEmailAddress function" & vbCrLf & vbCrLf _ 
      & "Error#: " & Err.Number & vbCrLf & vbCrLf & Err.Description 
    End Function 
+0

爲什麼你認爲OP需要布爾結果? –

+0

謝謝!我添加了布爾值來檢查數組中的哪個元素包含郵件地址,然後複製它 它現在可用! – Ollpej

0

得到它打印出這個代碼mailaddress: 感謝BRAX!

Function isEmail(ByVal data As String) 

Dim mailReg As Object 
Set mailReg = CreateObject("VBScript.RegExp") 

Dim regpattern As String 
regpattern = "^[_a-z0-9-]+(.[a-z0-9-]+)@[a-z0-9-]+(.[a-z0-9-]+)*(.[a-z]{2,4})$" 'Expression ok 

Dim arr1() As String 
Dim element As Variant 
Dim strInput As String 

arr1() = Split(data, " ") 

For Each element In arr1 

    strInput = element 
    mailReg.IgnoreCase = True 
    mailReg.Global = True 
    mailReg.Pattern = regpattern 

    If mailReg.Test(strInput) = True Then 

    MsgBox (strInput) 
    End If 
Next element 
End Function