Applying styles through VBA

D

DianePDavies

I have a generated text file. When imported in word, I would like to apply
styles to the paragraphs.
I can insert codes to identify the style to apply - e.g. "#H1" for my
"heading 1" - these codes can then be cleaned up afterwards.
Any hints on hwo to do that in an easy way?
 
G

Graham Mayor

If you setup a table with the codes in the first column and the associated
styles in the second then you can either select the code and rely on the
fact that replace will apply the style to the whole of the paragraph or you
could find the code and select the paragraph as a range then format that.

The following macro uses the first method to format the paragraph then
remove the code.
The table document - here "D:\My Documents\Test\Codes.doc"
is configured as follows
Col1 Col2
#H1 Heading 1
#H2 Heading 2
#BT Body Text
#N Normal
etc

For testing the codes were added to the start of the paragraph.

Dim ChangeDoc As Document, RefDoc As Document
Dim cTable As Table
Dim rCode As Range
Dim rStyle As Range
Dim i As Long
Dim sFname As String

sFname = "D:\My Documents\Test\Codes.doc"
Set RefDoc = ActiveDocument
Set ChangeDoc = Documents.Open(sFname)
Set cTable = ChangeDoc.Tables(1)
RefDoc.Activate
For i = 1 To cTable.Rows.Count
Set rCode = cTable.Cell(i, 1).Range
rCode.End = rCode.End - 1
Set rStyle = cTable.Cell(i, 2).Range
rStyle.End = rStyle.End - 1
With Selection
.HomeKey wdStory
With .Find
.ClearFormatting
.Replacement.ClearFormatting
.Replacement.Style = rStyle
.Execute findText:=rCode, _
ReplaceWith:="", _
Replace:=wdReplaceAll, _
MatchWholeWord:=True, _
MatchWildcards:=False, _
Forward:=True, _
Wrap:=wdFindContinue
.Replacement.ClearFormatting
.Execute findText:=rCode, _
ReplaceWith:="", _
Replace:=wdReplaceAll, _
MatchWholeWord:=True, _
MatchWildcards:=False, _
Forward:=True, _
Wrap:=wdFindContinue
End With
End With
Next i


--
<>>< ><<> ><<> <>>< ><<> <>>< <>><<>
Graham Mayor - Word MVP


<>>< ><<> ><<> <>>< ><<> <>>< <>><<>
 
T

tfsjohan

Why dont you create the text file as HTML? I mean, if you can put in
#h1, #h2, why not just use HTML like
<h1>Heading 1</h2>
<h2>Heading 2</h2>

Word can open HTML files without problem. If you need specific
formatting then use the Document.AttactedTemplate property to use a
template with the correct styles.
 
D

DianePDavies

The HTML may work. Do you happen to hava a sample - or how do I see a sample
of that somewhere else?

Many years ago I used the product "Book Master" for a similar task - that is
a text formatting program with similar codelogic as HTML I believe...
 

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