2015-12-14 24 views
1

我的Word宏有一個有趣的問題。我有代碼來查找標題1樣式,並用軟返回替換硬返回。 (這是爲了當我這樣做了,它會隨着故事的標題被格式化的內容的表,然後筆者都在一行。)Word Macro替換軟標題中的硬返回將改變標題樣式類型

這是我的代碼至今:

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?

+0

我還沒有嘗試過,但在我看來,你應該能夠指定.Replacement.Style =「標題1」,並且將被應用爲部分執行... –

回答

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 
+0

這工作很好!謝謝! –

+0

@JenniferMacDonald:歡迎來到Stack Overflow!很高興你解決了你的問題。你可以幫助每個人,如果你upvote有用的答案,並標記答案,解決您的問題作爲接受的答案。謝謝。 –

+0

哎呀,我剛剛發現一個小問題。這似乎只是爲了找到第一個替代品。我在While循環中設置了一個斷點,它只做一次。 –