2015-01-02 65 views
3

我期待在Excel中創建用戶定義的函數在Excel的範圍替換(2010,Visual Basic中7)呼籲CODEMATCH即會正則表達式匹配和使用Visual Basic功能

1. Take a range as an input 
2. Preserve the structure of the range when outputting 
3. On each value in the range: 
    a. If the value matches [matchPattern]: 
     i. regex match the value against [matchPattern] and store it as [var1] 
     ii. regex replace [var1] against [stripPattern] and store it as [var2] 
     iii. return [var2] 
    b. If the value does not match [matchPattern]: 
     i. return an empty value 

Where 
    matchPattern = "^[^A-Z0-9:]*[A-Z0-9][^A-Z0-9:]*[A-Z0-9]?" 
    stripPattern = "[^A-Z0-9]*" 

AndWhere 
    RegEx match is not global and respects case 
    RexEx replace is global and respects case 

Such that 
    "Nobody Cares about Bob" returns "NC" 
    "1 Duck for Jody" returns "1D" 
    "Apples: I Don't Like Them" returns "A" 
    "foobar" returns "" 

部分我的痛苦是我是新來的Visual Basic。我認爲,我的一部分痛苦來自Visual Basic中存在的RegEx的多個版本,並且不知道哪個版本需要哪些屬性。

我試圖建立功能最多的複雜程度,這是據我可以得到我打了一個堅不可摧的磚牆前:

Function CODEMATCH(ByVal valueIN As String) As String 

Set matchRegEx = New RegExp 
    matchRegEx.Pattern = "(sdi \d+)" '<--what's giving me difficulty 
    matchRegEx.Global = False 
    matchRegEx.IgnoreCase = False 

Set matches = matchRegEx.Execute(valueIN) 

If matches.Count <> 0 Then 
    CODEMATCH = matches.Item(0).SubMatches.Item(0) 
Else 
    CODEMATCH = "" 
End If 

End Function 

的代碼,因爲它是作品,但它贏得了」讓我使用我之前定義的matchPattern。除此之外,我仍然需要採用它來執行正則表達式替換,並採用它來處理範圍而不是單個單元格。

+1

難道只是我,還是會'VAR1 = regex.Match(valueIn,matchPattern); var2 = regex.Replace(var1,stripPattern,「」)'太明顯了? –

+0

爲什麼不把'matchPattern As String'作爲函數的另一個輸入並將它與'matchRegEx.Pattern = matchPattern'一起使用? – TheEngineer

+0

請參閱下文,我使用了兩個步驟的過程,一個用於匹配的Execute和一個用於替換條紋的Replace。不需要submatches – brettdj

回答

1

這是怎麼回事? :)

Function CODEMATCH(ByVal valueIN As String) As String 

Dim strTemp As String 
Set matchRegEx = New RegExp 
With matchRegEx 
    .Pattern = "[^A-Z0-9:]*[A-Z0-9][^A-Z0-9:]*[A-Z0-9]?" 
    .Global = False 
    .IgnoreCase = False 
If .Test(valueIN) Then 
    Set matches = .Execute(valueIN) 
    .Pattern = "[^A-Z0-9]*" 
    .Global = True 
    strTemp = matches(0) 
    CODEMATCH = .Replace(strTemp, vbNullString) 
Else 
CODEMATCH = vbNullString 
End If 
End With 

End Function 

測試

Sub Test() 
Debug.Print CODEMATCH("Nobody Cares about Bob") 
Debug.Print CODEMATCH("1 Duck for Jody") 
Debug.Print CODEMATCH("Apples: I Don't Like Them") 
Debug.Print CODEMATCH("foobar") 
End Sub 
+0

該代碼可以很好地工作......直到能夠將範圍而不是字符串作爲輸入;並輸出一個範圍。我知道它不僅僅需要'CODEMATCH(ByVal valueIN As Range)'來輸出一個範圍,因爲'CODEMATCH =',但我不知道該怎麼做。 –

+0

@BrandonLebedev如果您的數據在'A1:A10'等等,然後在B1 put ='CODEMATCH(A1)'中,並複製到B10。或者你是否希望以編程方式執行此操作 – brettdj

+0

最初的規範是用於以編程方式輸入和輸出數組的函數 –