使用正则表达式查找和替换的 VBA 反向引用

问题描述 投票:0回答:1

我想使用 VBA 和 regEx 标准化 Word 文档中某些文本的格式。例如,我的文档将包含“Qty #”、“Qty (#)”、“QTY(#)”、“qty of (#)”等文本字符串,其中 # 是 0-99 之间的整数值。我的目标是将这些字符串标准化为格式:“QTY (#)”。

下面是我尝试过的代码;但是,它不是反向引用数字,而是在括号内插入文字“$1”。我做了一些研究,看来 Range.Find 不支持反向引用。还有其他有效的方法吗?

Sub StandardizeQuantityFormat()
    Dim regEx As Object
    Set regEx = CreateObject("VBScript.RegExp")
   
    ' Define the regular expression pattern to match various quantity formats.
    regEx.Pattern = "Qty\s+(\d{1,2})|Qty\s+\((\d{1,2})\)|QTY\((\d{1,2})\)|qty of\s+\((\d{1,2})\)"
    regEx.IgnoreCase = True
    regEx.Global = True
   
    ' Define the desired format to replace found patterns.
    Dim replacementFormat As String
    replacementFormat = "QTY ($1)"
   
    ' Access the document's content.
    Dim docContent As Range
    Set docContent = ActiveDocument.Content
   
    ' Execute the Find and Replace using the RegExp.
    Dim match As Object
    For Each match In regEx.Execute(docContent.Text)
        With docContent.Find
            .Text = match.Value ' The text to find
            .Replacement.Text = replacementFormat
            .Forward = True
            .Wrap = wdFindContinue
            .Format = False ' Make sure to set Format to False to avoid formatting issues
            .Execute Replace:=wdReplaceAll
        End With
    Next match

    Set regEx = Nothing
    MsgBox "Quantity formats have been standardized."
End Sub
regex vba ms-word find backreference
1个回答
0
投票

看来使用Word替换功能而不是RegExp(正则表达式)替换方法可能存在误解。

Option Explicit

Sub StandardizeQuantityFormat()
    Dim regEx As Object
    Set regEx = CreateObject("VBScript.RegExp")
   
    ' Define the regular expression pattern to match various quantity formats.
    regEx.Pattern = "Qty\s*(?:of\s+)*\(*(\d{1,2})\)*"
    regEx.IgnoreCase = True
    regEx.Global = True
     
    ' Access the document's content.
    Dim docContent As Range
    Set docContent = ActiveDocument.Content
   
    ' Execute the Find and Replace using the RegExp.
    Dim match As Object
    For Each match In regEx.Execute(docContent.Text)
        With docContent.Find
            .Text = match.Value ' The text to find
            .Replacement.Text = regEx.Replace(match.Value, "QTY ($1)")
            .Forward = True
            .Wrap = wdFindContinue
            .Format = False ' Make sure to set Format to False to avoid formatting issues
            .Execute Replace:=wdReplaceAll
        End With
    Next match

    Set regEx = Nothing
    MsgBox "Quantity formats have been standardized."
End Sub

enter image description here

© www.soinside.com 2019 - 2024. All rights reserved.