Excel – 使用字典值进行正则expression式replace

我们试图自动地根据VBA字典自动翻译每个Excel单元格中的某个string的某个部分。

原始string示例:

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 

正则expression式定义如下:

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

我testing了一下,效果很好: http : //refiddle.com/im7s

该字典是从另一个excel spreasheet构build的。 示例键/值对是:

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

但是我找不到用这些字典键来replace原始string的方法。 下面的12行是我testing过的,但是找不到字典值…

 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 

任何指导,以解决这个问题非常感谢。 谢谢!

我不认为你需要这个正则expression式。 当我翻译的时候,我通常只是用蛮力replace。

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

等等。
而一旦所有的replace已经完成,你知道它已经翻译了excic的abreviations。
如果WO不在string中,则replace将失败,并继续下一个。

这里有一个基本概述:

 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