Excel - 使用字典值替换正则表达式

时间:2016-08-19 03:38:01

标签: excel vba excel-vba

我们正在尝试根据VBA字典自动翻译每个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

非常感谢任何解决此问题的指导。谢谢!

2 个答案:

答案 0 :(得分:1)

我认为你不需要正则表达式。当我翻译时,我通常只使用蛮力和替换。

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

等。
一旦完成所有替换,你就知道它已经翻译了那些令人兴奋的缩影 如果WO不在字符串中,那么替换将失败并继续下一个。

答案 1 :(得分: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