2016-08-19 29 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