Search code examples
vbams-wordnewlineparagraph

Replace new lines with paragraphs


I need to do the following in a Word Macro.

I need to go through a Word document and change certain paragraphs based on their parameters. If the font size of a paragraph is 19.5, the paragraph must get style Heading 1. The next paragraph will be Heading 2, and the next after it -- Heading 3. The other text will remain to have style "Normal".

Wrote the following Macro:

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

The problem is that sometimes the text contains a paragraph and sometimes just a new line. Trying to figure out to replace all new lines with paragraphs. Would appreciate any help.

Thank you!


Solution

  • It sounds like you mean the entire document: "replace all new lines with paragraphs"

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

    Note: Your code is using ActiveDocument a lot. It would be more efficient and safer to assign this to a variable:

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