我們嘗試基於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,根據需要運行替換。 –