Insert Text with Paragraph Format

L

LA Lawyer

I have a sting text variable where lines are already separated by carriage
returns. I want to insert this text into Word 2007 where the separated lines
are each recognized as paragraphs and the paragraph style is applied.

I know that I do this by replacing each carriage return with two carriage
returns and a tab (i.e., a paragraph), but it clearly would be cleaner to
apply the paragraph style.

How is this done?
 
D

Doug Robbins - Word MVP

If you use:

Dim strtext As String
strtext = "This is the first line" & vbCr & "This is the second line"
Selection.Range.Style = "Heading 1"
Selection.Range.Text = strtext

you will get two paragraphs, one containing

This is the first line

and the other containing

This is the second line

with both of them formatted with the Heading 1 style.

--
Hope this helps,

Doug Robbins - Word MVP

Please reply only to the newsgroups unless you wish to obtain my services on
a paid professional basis.
 
J

Jay Freedman

I have a sting text variable where lines are already separated by carriage
returns. I want to insert this text into Word 2007 where the separated lines
are each recognized as paragraphs and the paragraph style is applied.

I know that I do this by replacing each carriage return with two carriage
returns and a tab (i.e., a paragraph), but it clearly would be cleaner to
apply the paragraph style.

How is this done?

Declare a Range object and set it to the spot where the string will be
inserted. This might be the cursor location (represented by
Selection.Range, which you might have to collapse if it's extended
over existing text) or the result of a Find operation or something
else. Let's say you go for the cursor:

Dim myRange As Range
Set myRange = Selection.Range
myRange.Collapse Direction:=wdCollapseEnd

And insert the string:

myRange.Text = myString

It would be a good idea to make sure the string ends with a carriage
return, so it doesn't blend into the existing paragraph that follows
the insertion.

Then apply the style (Body Text, for example), which presumably has
been defined with Space Before or Space After and a first-line indent:

myRange.Style = ActiveDocument.Styles("Body Text")
 

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