2014-01-08 39 views
2

我想匹配的是這樣的正則表達式:^[a-zA-Z]{2}[0-9]{10}$使用喜歡比較的字符串在Excel

例如,如何測試的E2內容是否像[A-Za-z][A-Za-z]##########,我可以換行到IF聲明?

+2

澄清你的問題吧。你可以把一些有效的輸入和輸出?如果這個'IF'在這裏返回1? – Jerry

+0

@Jerry如果正則表達式在Excel中匹配我想要五個'TRUE'或'FALSE'。我的'E'列包含與正則表達式匹配的數字。 – user2051347

+2

只是爲了檢查:如果E2有文字'^ [a-zA-Z] {2} [0-9] {10} $',你想得到'TRUE'? – Jerry

回答

0

使用此:

Function regxMatch(Value As String, Pattern As String, Optional IgnoreCase As Boolean = False) 
    Dim r As New VBScript_RegExp_55.RegExp 
    r.Pattern = Pattern 
    r.IgnoreCase = IgnoreCase 
    If r.Test(Value) Then 
     M = "Matches '" & Pattern & "'" 
    Else 
     M = "" 
    End If 
End Function 

功能應該是不言而喻的!

+1

Thx很多!優秀的答案! – user2051347

+1

@ user2051347您可能想要重命名該函數,因爲已經有一個名爲'Match'的函數。也許像'regexmatch'。 – Jerry

+1

@Jerry如何在我的vba代碼上使用此功能?我在vba編輯器中將它作爲模塊發佈,但是我無法打開該功能? – user2051347

0

你可以這樣運行一個較短的測試:

Function regexTest(strIn As String, strPattern As String) As Boolean 
    Dim objRegex As Object 
    Set objRegex = CreateObject("vbscript.regexp") 
    objRegex.Pattern = strPattern 
    regexTest = objRegex.test(strIn) 
End Function 

測試代碼

Sub TestME() 
MsgBox regexTest("ZAE000006284", "^[a-zA-Z]{2}[0-9]{10}$") ' False 
MsgBox regexTest("ZA0000000628", "^[a-zA-Z]{2}[0-9]{10}$") ' True 
End Sub