我们尝试基于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
任何指导搞定这个问题解决了,非常感谢。谢谢!
不能代替所有一次性的字典键的:你需要更换每一个设置。使用该模式获取Matches集合,然后循环查看每个SubMatches,根据需要运行替换。 –