Alignment of Text using VBA

R

Robert

I have written my first long(ish) subroutine and
everything works correctly except for a few lines which
generate Compile errors whichever way I try to write them.

I need to insert a short, centred title at the very top
of (at this stage) an otherwise empty document. I need to
insert one empty line (Paragraph) after it and finish by
aligning it Left ready for the next lot of text.

If I position the IP using ActiveDocument.Paragraphs(1),
then I cannot use InsertBefore/After to insert the Title.
Similarly, if I use ActiveDocument.Range(0,0).Select,
then I cannot use Alignment = wdAlign... to position the
Title. TypeText also doesn't work with the particular
combinations I have tried. I am very confused.

Could some kind person show me a few lines of code to
achieve this. I should be most grateful.
 
J

Jay Freedman

Hi Robert,

I'd consider pushing the insertion point around and using TypeText to be the
least desirable method of doing this. Using direct formatting just makes it
worse.

First, make sure the template on which your document is based has the styles
needed for everything in the document. There are plenty of built-in styles,
and you can easily modify them or define new ones as needed.

Insert the text (as plain text) by assigning it to the .Text property of a
suitable range. Then do the formatting by applying styles where they're
needed. As an example:

With ActiveDocument
' fill in text
' each vbCr is like hitting Enter
.Paragraphs(1).Range.Text = "Moby-Dick" & vbCr
.Paragraphs(2).Range.Text = "Or, The Whale" & vbCr
.Paragraphs(3).Range.Text = "Start Here!"

' apply styles
.Paragraphs(1).Style = .Styles("Title")
.Paragraphs(2).Style = .Styles("Subtitle")
' .Para(3) remains in default Normal style

' put the cursor where you want it
.Paragraphs(3).Range.Select
End With
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top