Word VBA - 查找文本以更改样式

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

我有一个Word文档,其中一些段落的格式为“标题2”,这些段落出现在目录中,但不应该出现,所以我编写了一些宏代码来循环查找这些项目并将样式更改为“正常”然后重新应用与“标题 2”相同的格式。一种是客户希望全部大写的超链接。当找到以文本“DESCRIPTION”开头的段落时,循环应停止。我的代码如下,ActiveSource 是当前文档。问题是它没有找到要更改的段落。相反,它似乎只找到零长度字符串。我的代码有什么问题?

    Dim AllCaps As Boolean
    Set FindRange = ActiveSource.Content
    With FindRange.Find
         .Style = ActiveSource.Styles("Heading 2")
         .Forward = True
         .Format = True
    End With

    Do While FindRange.Find.Execute
        With FindRange.Find
            If Left(.Text, 11) = "DESCRIPTION" Then GoTo UpdateTOC
            AllCaps = .Font.AllCaps
            .Style = ActiveSource.Styles("Normal")
            .Font.Name = "Arial"
            .Font.Size = 12
            .Font.Bold = True
            .Font.Underline = True
            If AllCaps Then .Font.AllCaps = True
        End With
    Loop
UpdateTOC:
vba ms-word
1个回答
0
投票

我相信实现您需要的更好的方法是循环遍历所有段落,而不是使用 Find 对象。

Public Sub FindH2()
    Dim ActiveSource As Document
    Dim prg As Paragraph
    
    Set ActiveSource = ThisDocument
    
    For Each prg In ActiveSource.Paragraphs
        If Left(prg.Range.Text, 11) = "DESCRIPTION" Then
            GoTo UpdateTOC
        End If
        If prg.Style = "Heading 2" Then
            prg.Style = "Normal"
            prg.Range.Font.Name = "Arial"
            prg.Range.Font.Size = 12
            prg.Range.Font.Bold = True
            prg.Range.Font.Underline = True
            prg.Range.Font.AllCaps = True
        End If
    Next prg
  
    
    
UpdateTOC:
    Exit Sub
End Sub

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