2016-04-23 125 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

您的答复非常感谢! –