Regex Microsoft Word without destroying document formatting

后端 未结 1 436
礼貌的吻别
礼貌的吻别 2021-01-02 19:56

It\'s well known that word\'s find and replace \"wildcards\" features suffer some severe limitations.

The following code implements true regex find and replace in a

相关标签:
1条回答
  • 2021-01-02 20:57

    @Some_Guy: thanks for asking this question, I had a similar problem and your post saved me quite a bit of time.

    This is the kludge I came up with:

    Sub RegEx(Before As String, After As String, _
              Optional CaseSensitive As Boolean = False, _
              Optional Location As Range = Nothing, _
              Optional DebugMode As Boolean = False)
    
        'can't declare activedocument.range in parameters
        If Location Is Nothing Then Set Location = ActiveDocument.Range
    
        Dim j As Long
        Dim regexp As Object
        Dim Foundmatches As Object
        Dim Match As Object
        Dim MatchRange As Range
        Dim offset As Integer: offset = 0
        Set regexp = CreateObject("vbscript.regexp")
    
        With regexp
            .Pattern = Before
            .IgnoreCase = Not CaseSensitive
            .Global = True
    
            'set foundmatches to collection of all regex matches
            Set Foundmatches = .Execute(Location.Text)
            For j = Foundmatches.Count - 1 To 0 Step -1
    
                If DebugMode = True Then
                    'debugging
                    Debug.Print Foundmatches(j), .Replace(Foundmatches(j), After)
                Else
                    'REAL LIFE
    
                    'run a plain old find/replace on the found string and eplace strings
                    With ActiveDocument.Range.Find
                        .ClearFormatting
                        .Replacement.ClearFormatting
                        .Replacement.Font.Hidden = True
                        .Text = Foundmatches(j)
                        .Replacement.Text = regexp.Replace(Foundmatches(j), After)
                        .Execute Replace:=wdReplaceAll
                    End With
                End If
            Next j
        End With
    End Sub
    

    Basically I use a simple find/replace with strings that match each item found (and would be replaced) with a regex, would decent support for it exist in Word). Note that any text replaced takes on the formatting of the first replaced character, so if the first word is in bold, then all the replaced text will be bold.

    0 讨论(0)
提交回复
热议问题