替换VBA中的功能

时间:2017-08-17 15:43:34

标签: excel-vba vba excel

我正在尝试清理一些数据,并可以使用替换功能的一些帮助。

如果我需要将excel中的单元格值替换为“Paul the Optometrist Pa”改为“Paul the Optometrist PA”,我会使用类似的东西

Replace(t, " Pa", " PA")

问题在于它还将保罗的字母改为“PAul”。显然我不希望这样。有没有办法阻止它改变字符串中没有特别是“PA”的东西,除了它之前和之后只有空格?

1 个答案:

答案 0 :(得分:1)

此RegEx将与字符串中的Pa匹配,并将其替换为PA。这可以很容易地更新以循环遍历您的数据集

Sub RegExExample()               
    With CreateObject("VBScript.RegExp")
        .Global = True
        .IgnoreCase = False
        .Pattern = "(Pa)\b"

        MsgBox .Replace("Paul the Optometrist Pa", "PA")
    End With
End Sub

将输出Paul the Optometrist PA