2016-04-23 127 views
0

我需要在Word宏中執行以下操作。Word VBA宏:用段落替換新行

我需要通過一個Word文檔並根據它們的參數改變某些段落。如果段落的字體大小爲19.5,則該段落必須得到樣式標題1.下一段落爲標題2,下一段落後面 - 標題3.其他文本將保持樣式爲「正常」。

寫了下面的宏:

Sub styles_temp() 

' Declare a paragraph 
Dim p As Paragraph 

' Declare the current size. 
Dim currentSize As Single 

'Iterate through the text and print each paragraph 
For Each p In ActiveDocument.Paragraphs 

' Determine current size of the paragraph 
currentSize = p.Range.Font.Size 

' If size is 19.5, it will be Heading 1 
If currentSize = 19.5 Then 

    p.Range.Style = ActiveDocument.Styles("Heading 1") 

    ' Next Line is Heading 2 
    p.Next.Range.Style = ActiveDocument.Styles("Heading 2") 


ElseIf p.Range.Style = "Heading 2" Then 
    p.Next.Range.Style = ActiveDocument.Styles("Heading 3") 

End If 

Next p 

End Sub 

的問題是,有時文本中包含一個段落,有時只是一個新的生產線。試圖找出用段落替換所有新行。將不勝感激任何幫助。

謝謝!

回答

1

這聽起來像你的意思是整個文檔:

ActiveDocument.Content.Find.Execute FindTExt:="^l", ReplaceWith:="^p", Replace:=wdReplaceAll 

注「與段落全部更換新的線路」:您的代碼是用ActiveDocument了很多。這將是更有效和更安全的這個分配給一個變量:

Dim doc as Word.Document 
Set doc = ActiveDocument 
doc.Content.Find.Execute FindTExt:="^l", ReplaceWith:="^p", Replace:=wdReplaceAll 
+0

您的答覆非常感謝! –