Changing style of words, depending on whether the word is bold or not, is slow

前端 未结 1 1734
耶瑟儿~
耶瑟儿~ 2021-01-26 16:51

I´d like to change the style of several words within the active document.

  • Each word could appear more than once.
  • Some words are bold and some are unbold
相关标签:
1条回答
  • 2021-01-26 17:20

    The logic of the code in the question is faulty. Find needs to have actually located the search term before code can test whether it's bold or not bold.

    Two basic approaches would be possible

    1. Search the term, when found perform the test and apply the style
    2. Search each term twice, once for bold and once for not bold

    You'd need to test, but based on experience I believe the second approach would be faster as it can use ReplaceAll.

    The code below demonstrates the principle, based on the code in the question. Note that it uses a Range object, rather than Selection as this is generally more efficient.

    Sub FindReplaceFormattingVariations()
        Dim rng As Word.Range
        Dim searchTerm As String
        Dim Arr(1 to 200)
    
        Arr(1) = "Word1"
        Arr(2) = "Word2"
        .
        .
        .
        Arr(200) = "Word200"
    
    For i = 1 To Ubound(Arr) 
        searchTerm = Arr(i)
        Set rng = ActiveDocument.content
        With rng.Find
            .ClearFormatting
            .Replacement.ClearFormatting
            .Text = searchTerm
            .Font.Bold = True
            .Replacement.Style = ActiveDocument.Styles("StyleA")
            .Execute Replace:=wdReplaceAll
        End With
    
        With rng.Find
            .ClearFormatting
            .Replacement.ClearFormatting
            .Text = searchTerm
            .Font.Bold = False
            .Replacement.Style = ActiveDocument.Styles("StyleB")
            .Execute Replace:=wdReplaceAll
        End With
    Next    
    End Sub
    
    0 讨论(0)
提交回复
热议问题