在Word宏中使用VB正则表达式时如何保留粗体,斜体等

时间:2019-03-04 16:02:35

标签: vba ms-word

这是宏。 它会按我的要求进行替换,但是任何粗体或斜体匹配项都将替换为纯文本。

    Sub TEST_All_TEXT_CONVERT_COMMA_TO_HYPHEN_AT_PARAGRAPH_START()
    '
    ' TEST_All_TEXT_CONVERT_COMMA_TO_HYPHEN_AT_PARAGRAPH_START
    '
    '
Dim regExp As Object
Set regExp = CreateObject("vbscript.regexp")

With regExp
'Generic pattern
.Pattern = "(\r)([1-3 ]*[^ ]{1,15} )(\d+:\d+), (\d+\.)"
.Global = True
Selection.WholeStory
Selection = .Replace(Selection, "$1$2$3-$4")

End With
Selection.Collapse Direction:=wdCollapseEnd
'MsgBox "Done"
    End Sub

1 个答案:

答案 0 :(得分:0)

尝试一下:

Sub TEST_All_TEXT_CONVERT_COMMA_TO_HYPHEN_AT_PARAGRAPH_START()
    Dim regExp As Object
    Set regExp = CreateObject("vbscript.regexp")

    With regExp
        'Generic pattern
        .Pattern = "(\r)([1-3 ]*[^ ]{1,15} )(\d+:\d+), (\d+\.)"
        .Global = True
        Selection.WholeStory
        'Selection = .Replace(Selection, "$1$2$3-$4")

        Dim Matches As Object
        Dim Match As Object

        Set Matches = .Execute(Selection)
        For Each Match In Matches
            Selection.Start = Match.FirstIndex
            Selection.End = Match.FirstIndex + Match.Length - 1
            Selection = .Replace(Selection, "$1$2$3-$4")
        Next Match
    End With
    Selection.Collapse Direction:=wdCollapseEnd
    'MsgBox "Done"
End Sub

我不太确定它是否能正常工作,但希望您能解决问题。 它使用Execute方法返回一组匹配项,而不是一次性处理所有文本,然后逐个处理。