Jean-Guy
Tue Feb 13 16:42:44 CST 2007
Brian Durham was telling us:
Brian Durham nous racontait que :
> I'm creating a Word doc with some VBA code. I'm getting all the
> content correctly, but I need to apply some styles. The finished
> product could be any number of the following chunks of text.
>
> Section Label
>
> Description: <some variable length text>
> Notes: <some variable length text>
> Version: <some variable length text>
> Table with 2 columns and n rows
>
> Section Label, Description, Notes and Version need to have the same
> style applied. The text after the colons needs a different style.
> Can I apply styles as I write these lines with Selection.TypeText?
> Or should I write all the content and then rummage through the entire
> document object searching for different pieces of text and apply the
> styles then? I've tried various things with the Selection and Range
> objects with unexpected results.
>
> Thanks,
>
> Brian
It is easier to format as you go along, but you should be using the Range
object instead of the Selection one.
Every time you insert text, the range matches the inserted text and so it is
easy to format it. See the example below that will add text at the end of a
document:
'_______________________________________
Sub WriteFormatText()
Dim rgeDoc As Range
Set rgeDoc = ActiveDocument.Range
With rgeDoc
.InsertParagraphAfter
.Collapse wdCollapseEnd
.InsertAfter "Section Label"
.Style = "Label"
.InsertParagraphAfter
.InsertParagraphAfter
.Collapse wdCollapseEnd
.InsertAfter "Description:"
.Style = "Label"
.Collapse wdCollapseEnd
.InsertAfter " <some variable length text>"
.Style = "Value"
.InsertParagraphAfter
.Collapse wdCollapseEnd
.InsertAfter "Notes:"
.Style = "Label"
.Collapse wdCollapseEnd
.InsertAfter " <some variable length text>"
.Style = "Value"
.InsertParagraphAfter
.Collapse wdCollapseEnd
.InsertAfter "Version:"
.Style = "Label"
.Collapse wdCollapseEnd
.InsertAfter " <some variable length text>"
.Style = "Value"
.InsertParagraphAfter
.Collapse wdCollapseEnd
End With
End Sub
'_______________________________________
--
Salut!
_______________________________________
Jean-Guy Marcil - Word MVP
jmarcilREMOVE@CAPSsympatico.caTHISTOO
Word MVP site:
http://www.word.mvps.org