Create style if not already present

M

MMH

Hello all

I am trying to work out the VBA code to see if a style (FaxHeader) exists in
a particular document, and if it does not, create the style.

I can work out the code for creating a new style, it is just the code to
check if it already exists that is giving me problems. Any help would be
much appreciated.

Thanks in advance,
MMH.
 
J

Jay Freedman

Hello all

I am trying to work out the VBA code to see if a style (FaxHeader) exists in
a particular document, and if it does not, create the style.

I can work out the code for creating a new style, it is just the code to
check if it already exists that is giving me problems. Any help would be
much appreciated.

Thanks in advance,
MMH.

Here are two ways to go about it:

(1) Iterate through the entire Styles collection, checking to see
whether any of them have the name you want to use...

Dim oStyle As Style, NewStyle As Style
Dim bFound As Boolean
Dim strNewStyle As String

strNewStyle = "FaxHeader"

For Each oStyle In ActiveDocument.Styles
If LCase(oStyle.NameLocal) = LCase(strNewStyle) Then
bFound = True
Exit For
End If
Next oStyle

If Not bFound Then
Set NewStyle = ActiveDocument.Styles.Add( _
Name:=strNewStyle, _
Type:=wdStyleTypeParagraph)
NewStyle.BaseStyle = ActiveDocument.Styles("Normal")
End If

(2) Use error-trapping. Try to use the style; if it doesn't exist, the
Err.Number property is assigned a nonzero value...

On Error Resume Next
If LCase(strNewStyle) <> "normal" Then
rgAT.Style = ActiveDocument.Styles(strNewStyle)
If Err.Number <> 0 Then
Err.Clear
' define & apply style
Set NewStyle = ActiveDocument.Styles.Add( _
Name:=strNewStyle, _
Type:=wdStyleTypeParagraph)
NewStyle.BaseStyle = ActiveDocument.Styles("Normal")
On Error Resume Next
rgAT.Style = ActiveDocument.Styles(strNewStyle)
End If
End If
 

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