Vba Word宏将标题中的硬回车替换为软回车将更改标题样式类型

Vba Word宏将标题中的硬回车替换为软回车将更改标题样式类型,vba,ms-word,Vba,Ms Word,我的Word宏有一个有趣的问题。我有代码来寻找标题1样式,并用软返回替换硬返回。(当我整理目录时,它的格式是故事标题,然后是作者,都在一行上。) 这是我迄今为止的代码: Selection.Find.ClearFormatting Selection.Find.Style = ActiveDocument.Styles("Heading 1") Selection.Find.Replacement.ClearFormatting With Selection.Find .Text = "

我的Word宏有一个有趣的问题。我有代码来寻找标题1样式,并用软返回替换硬返回。(当我整理目录时,它的格式是故事标题,然后是作者,都在一行上。)

这是我迄今为止的代码:

Selection.Find.ClearFormatting
Selection.Find.Style = ActiveDocument.Styles("Heading 1")
Selection.Find.Replacement.ClearFormatting
With Selection.Find
    .Text = "^p"
    .Replacement.Text = "^l"       
    .Forward = True
    .Wrap = wdFindContinue
    .Format = True
    .MatchCase = False
    .MatchWholeWord = False
    .MatchWildcards = False
    .MatchSoundsLike = False
    .MatchAllWordForms = False
    .Execute Replace:=wdReplaceAll
End With
这是应该的,但它也将我的标题1更改为标题2样式。(显然这就是Word的工作原理)


我正在寻找关于如何进行替换的想法,并将其保留为标题1

在这种情况下,简单的全部替换是不行的。一种解决方案是搜索文档中的相关位置,用手动换行符逐个替换段落,然后恢复所需的格式。可以使用以下宏执行此操作:

Dim nextParagraphRange As Range

With Selection.Find
    .ClearFormatting
    .Style = ActiveDocument.Styles("Heading 1")
    .Text = "^p"
    .Forward = True
    .Wrap = wdFindContinue
    .Format = True
    .MatchCase = False
    .MatchWholeWord = False
    .MatchWildcards = False
    .MatchSoundsLike = False
    .MatchAllWordForms = False

    Do While .Execute(Replace:=wdReplaceNone)

        ' check whether there is another paragraph
        ' following the "Heading 1" paragraph
        Set nextParagraphRange = Selection.Range.Next(wdParagraph)
        If Not nextParagraphRange Is Nothing Then
            ' check if the following paragraph is a "Heading 2"
            If nextParagraphRange.Style = "Heading 2" Then

                ' replace paragraph mark with manual line break
                Selection.Range.Text = Chr(11)

                ' restore original "Heading 1" style so that the
                ' paragraph still is level-1 in the ToC
                Selection.ParagraphFormat.Style = "Heading 1"

                ' move the Selection to the text that before was "Heading 2"
                Selection.Move wdCharacter
                Selection.MoveEnd wdParagraph
                Selection.MoveEnd wdCharacter, -1 ' don't include the paragraph mark

                ' re-apply "Heading 2" as direct formatting
                Selection.Style = "Heading 2"
            End If
        End If

    Loop
End With

我还没有尝试过,但在我看来,您应该能够指定.Replacement.Style=“Heading 1”,这将作为执行的一部分应用…@JenniferMacDonald:欢迎使用堆栈溢出!很高兴你的问题解决了。如果你投票选出有用的答案,并将解决问题的答案标记为已接受的答案,你可以帮助所有人。谢谢。哎呀,我刚发现一个小问题。这似乎只对找到的第一个进行替换。我在While循环中设置了一个断点,它只执行一次。@JenniferMacDonald:根据您的实际文档,您可能需要将循环体末尾的选择移动到段落后面,例如使用
selection.move wdparagration