Applying Styles to Text

E

ExcelMonkey

How do you apply a Style and then switch back to normal. I want to insert a
heading say "Summary". I want to apply a normal style to this, and then have
a carriage return and the switch to the Normal style. The code below does
provide a carriage return not does it switch the style.

MyDoc.Range.Style = "Normal"
MyApp.Selection.TypeText "Summary"

MyDoc.Range.Style = "Heading 1"
MyApp.Selection.TypeText "Other Text"


Thanks

EM
 
L

Lene Fredborg

Your description is a bit confusing. You are talking about Heading 1 and
Normal but I am not sure in which order you want to apply the styles. Below
you will find two different macros. The first one uses the Selection object
whereas the second uses the Range object.

Preconditions:
In both macros, it is assumed that the cursor be in an empty paragraph when
you start.

See the comments in the code for details. Note that the constants
wdStyleHeading1 and wdStyleNormal have been used for the style names – this
will make the macros work even if you do not have an English version of Word
(for example, “Heading 1†is named “Overskrift 1†in a Danish version. If a
macro tries to apply a style named “Heading 1â€, an error will occur.

It is generally better to use the Range object instead of the Selection
object. One import advantage is that you can more easily keep track of which
text you are manipulating.

------------------
Macro using the Selection object:

Sub CreateText_Selection()

With Selection
'Type text
.TypeText "Summary"
'Change the style of that paragraph to Heading 1
.Style = wdStyleHeading1
'Insert another paragraph
.TypeParagraph
'Type text
.TypeText "Other text"
'Change the style of that paragraph to Normal
.Style = wdStyleNormal
End With

End Sub

------------------
Macro using the Range object:

Sub CreateText_Range()

Dim oRange As Range

'Set the range to the selection
Set oRange = Selection.Range

With oRange
'Create two paragraphs with text - vbCr inserts a paragraph mark
'Start adding a new paragraph
.Text = "Summary" & vbCr & "Other text"

'Now the range holds two paragraphs
'Apply Heading 1 to the first and Normal style to the second
.Paragraphs(1).Style = wdStyleHeading1
.Paragraphs(2).Style = wdStyleNormal
End With

'Clean up
Set oRange = Nothing

End Sub

--
Regards
Lene Fredborg
DocTools - Denmark
www.thedoctools.com
Document automation - add-ins, macros and templates for Microsoft Word
 

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