2017-03-02 78 views
2

我正在寫一個excel宏程序,以便能夠搜索excel列表,並且除其他外,將匹配項(如果有的話)寫入不同單元格。在Excel中寫入幾個不同單元格的匹配項

我從this得到了很多幫助很好的解釋,但我無法弄清楚的是如何只給單元格寫正則表達式匹配。我當前的代碼在匹配後剪切字符串並將其寫入單元格。但我只想寫下匹配,沒有別的字符串。

這是我的代碼:

Private Sub simpleRegex() 
Dim strPattern As String 
Dim strReplace As String 
Dim regEx As New RegExp 
Dim strInput As String 
Dim Myrange As Range 

Set Myrange = ActiveSheet.Range("A1:A5") 

For Each cell In Myrange 
    strPattern = "(storlek|strl|stl|strlk|storleken|storl|size|storleksmärkt|storl|storlk|st)(.{0,2}?)((30|32|34|36|38|40|42|44|46|48|50))(.?)((30|32|34|36|38|40|42|44|46|48|50)?)" 

    If strPattern <> "" Then 
     strInput = cell.Value 
     strReplace = "$1" 

     With regEx 
      .Global = True 
      .MultiLine = True 
      .IgnoreCase = False 
      .Pattern = strPattern 
     End With 

     If regEx.test(strInput) Then 
      cell(1, 5).Value = 1 
      cell(1, 2).Value = regEx.Replace(strInput, "$1") 
      cell(1, 3).Value = regEx.Replace(strInput, "$2") 
      cell(1, 4).Value = regEx.Replace(strInput, "$3") 

     Else 
      cell(1, 6).Value = 1 
     End If 
    End If 
Next 
End Sub 

這是結果我在Excel中得到:

enter image description here

所以在A列中的紅色文字是從初始字符串的全場比賽,並B和D列中的紅色是分開的匹配。所以它幾乎就像我想要的那樣,但我想只在單元格B-D中匹配不是整個字符串。

對不起,瑞典的例子中,我的數據集來自瑞典的網站。但是我認爲你無論如何都會遇到問題?

+0

那你爲什麼要'替換'? '執行'並獲取匹配值。 –

+0

啊哈,您​​需要B-D列中的子匹配1至3。運行'regEx.Execute'並獲取這些值。 –

+0

謝謝你們幫助。我只是學習VB和正則表達式,所以我不知道如何使用execute方法。但現在我明白了,至少差不多!感謝您的幫助:D –

回答

0

您需要使用.regEx.Execute(str)並訪問SubMatches值:

Dim objMatchs As MatchCollection 
' ... 
Set objMatches = regEx.Execute(strInput) 
If objMatches.Count <> 0 Then 
    cell(1, 5).Value = 1 
    cell(1, 2).Value = objMatches(0).SubMatches(0) 
    cell(1, 3).Value = objMatches(0).SubMatches(1) 
    cell(1, 4).Value = objMatches(0).SubMatches(2) 
End If 

捕獲組ID與0的索引開始。

objMatches(0).SubMatches(0)表示獲得第一個匹配,第一個捕獲組的值爲

+0

謝謝,這工作完美! –

相關問題