Share via

Adding paragraphs to section

Anonymous
2018-04-20T19:39:03+00:00

Hi, I'm trying to write what I thought would be a simple, straightforward macro, but it's turning out to more complicated than anticipated, mostly because the Paragraphs.Add method seems to behave in mysterious ways.

Here's what I want to do: (1) add a new paragraph at the end of the first section, (2) add text to that new paragraph, (3) apply a custom heading style to the paragraph, and (4) repeat steps 1-3, though in that case using a body text style. Here's what I came up with:

Sub AddGrafs()

Dim Txt1 as String, Txt2 as String

Txt1 = "Heading text"

Txt2 = "Body text"

Set H1 = ActiveDocument.Styles("Custom heading style")

Set BT = ActiveDocument.Styles("Custom body text style")

Set rng = ActiveDocument.Content.Sections.First.Range

rng.end = rng.end - 1

With rng

  .Paragraphs.Add

  .Paragraphs.Last.Range.Text = Txt1

  .Paragraphs.Last.Style = H1

End With

Set rng = ActiveDocument.Content.Sections.First.Range

rng.end = rng.end - 1

With rng

  .Paragraphs.Add

  .Paragraphs.Last.Range.Text = Txt2

  .Paragraphs.Last.Style = BT

End With

End Sub

I've tried many variations of this macro, all to no avail. Help most appreciated!

Microsoft 365 and Office | Word | For home | Windows

Locked Question. This question was migrated from the Microsoft Support Community. You can vote on whether it's helpful, but you can't add comments or replies or follow the question.

0 comments No comments

Answer accepted by question author

Jay Freedman 207.7K Reputation points Volunteer Moderator
2018-04-21T01:23:26+00:00

In more than 20 years of VBA coding, I've never used .Paragraphs.Add -- it just seems to be doing things the hard way. The built-in constant vbCr represents a paragraph mark, and adding it to a string creates a new paragraph. If you use the range's .InsertAfter command, the inserted text extends the range, so there's also no need to redefine and adjust the range. One more thing: You should declare all your variables, not just the strings.

This version will do what you want:

Sub AddGrafs()

    Dim Txt1 As String, Txt2 As String

    Dim H1 As Style, BT As Style

    Dim rng As Range

    Txt1 = "Heading text"

    Txt2 = "Body text"

    Set H1 = ActiveDocument.Styles("Custom heading style")

    Set BT = ActiveDocument.Styles("Custom body text style")

    Set rng = ActiveDocument.Sections(1).Range

    rng.End = rng.End - 1

    With rng

        .InsertAfter Txt1 & vbCr

        .Paragraphs.Last.Style = H1

        .InsertAfter Txt2 & vbCr

        .Paragraphs.Last.Style = BT

    End With

End Sub

Was this answer helpful?

2 people found this answer helpful.
0 comments No comments

1 additional answer

Sort by: Most helpful
  1. Anonymous
    2018-04-21T20:16:22+00:00

    Thanks very much, that works nicely. I'll be steering clear of Paragraphs.Add from on!

    Was this answer helpful?

    0 comments No comments