2016-08-19 41 views
1

我們嘗試基於VBA字典自動地在每個Excel單元格中自動翻譯字符串的某個部分。Excel - 使用字典值進行正則表達式替換

原始字符串例子:

1.Outer Fabric:2% EA, 44% WO, 54% PES; Lining:4% EA, 96% RY 
Outside:2% EA, 98% WO 
1.Outer Fabric:27% PA, 73% WV; 2.Lining:100% CO; 2.Outer Fabric:100% AOS 

正則表達式定義爲:

Dim strPattern As String: strPattern = "(\d{1,3}\%\s+)(\w+)" 

我測試,它工作得很好:http://refiddle.com/im7s

字典是從另一構建的Excel spreasheet。示例鍵/值對是:

EA: Leather 
WO: Cloth 
PES: Polyester 
RY: Other 
... 

但我找不到一種方法來使用這些字典鍵來替換原始字符串。下面第12行是我測試過,但它無法找到字典值...

Dim strPattern As String: strPattern = "(\d{1,3}\%\s+)(\w+)" 
Dim strInput As String 
Dim Myrange As Range 

Set Myrange = ActiveSheet.Range("A2:A50") 
With regex 
    .Global = True 
    .MultiLine = True 
    .IgnoreCase = False 
    .Pattern = strPattern 
End With 
Dim strReplace As String: strReplace = "$1" & IIf(Dict.Exists("$2"), Dict("$2"), "$2") 

For Each cell In Myrange 
    If strPattern <> "" Then 
     strInput = cell.Value 
     cell.Value = regex.replace(strInput, strReplace) 
    End If 
Next 

任何指導搞定這個問題解決了,非常感謝。謝謝!

+0

不能代替所有一次性的字典鍵的:你需要更換每一個設置。使用該模式獲取Matches集合,然後循環查看每個SubMatches,根據需要運行替換。 –

回答

1

我不認爲你需要這個正則表達式。當我翻譯的時候,我通常只是用蠻力替換。

str = Replace (str, "EA", "Leather") 
str = Replace (str, "WO", "Cloth") 
str = Replace (str, "PES", "Polyester") 

等等
一旦全部替換已經完成,你知道它是翻譯的excist abreviations。
如果WO不在字符串中,則替換將失敗並繼續下一個。

+1

在這種情況下使用替換的問題不起作用。如果字符串包含「25%EA,35%EA,40%EA」,並且我想用LEA替換EA,則最終字符串將包含LLLEA – obvdso

+0

此外,要替換的字符串可能爲數千行,爲每個條目執行此操作是乏味的。 – obvdso

+1

LEA不是範圍的一部分。當你寫一個你不「等」的問題時,這一點非常重要。當有什麼是重要的。但是如果你替換「EA」,那麼你首先需要一個空間來解決你的問題。單調乏味,是的。但這就是翻譯的內容。我還沒有看到任何不安全的方法。因人而異。 – Andreas

1

這是一個基本的輪廓:

Sub Tester() 

    Dim regEx As Object, dict As Object 
    Dim matches, m 
    Dim c As Range 
    Dim s As String, mat As String 

    Set dict = CreateObject("scripting.dictionary") 
    dict.Add "EA", "Leather" 
    dict.Add "WO", "Cloth" 
    dict.Add "PES", "Polyester" 
    dict.Add "RY", "Leather" 

    Set regEx = CreateObject("vbscript.regexp") 
    regEx.Pattern = "(\d{1,3}\%\s+)(\w+)" 
    regEx.Global = True 
    regEx.IgnoreCase = True 
    regEx.MultiLine = True 

    For Each c In ActiveSheet.Range("A1:A10") 
     s = c.Value 
     Set matches = regEx.Execute(s) 
     If Not matches Is Nothing Then 
      'loop over each of the match objects 
      For Each m In matches 
       mat = m.submatches(1) '<<second submatch=material code 
       If dict.Exists(mat) Then 
        s = Replace(s, m, Replace(m, mat, dict(mat))) 
       End If 
      Next m 
     End If 
     c.Offset(0, 1).Value = s 
    Next c 

End Sub 
+0

這工作得很好。非常感謝,@ tim-williams – obvdso