我的Word Macro有一个有趣的问题。我有代码来寻找标题1样式并用软返回替换硬返回。 (当我对目录进行处理时,它将使用故事标题进行格式化,然后将作者全部放在一行上。)
到目前为止,这是我的代码:
this.functionName
这样可以正常工作,但它也会将我的标题1更改为标题2样式。 (显然这就是Word的工作方式)
我正在寻找关于如何进行替换的想法并将其保留为标题1?
答案 0 :(得分: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