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.

Re: Create style if not already present by Jay

Jay
Wed Jun 22 21:54:08 CDT 2005

On Wed, 22 Jun 2005 17:53:04 -0700, MMH
<MMH@discussions.microsoft.com> wrote:

>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

--
Regards,
Jay Freedman
Microsoft Word MVP FAQ: http://word.mvps.org

Re: Create style if not already present by MMH

MMH
Wed Jun 22 23:06:01 CDT 2005

Thank you - I used option 1 and it worked brilliantly.

MMH

"Jay Freedman" wrote:

> 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...
>
> (2) Use error-trapping. Try to use the style; if it doesn't exist, the
> Err.Number property is assigned a nonzero value...
>
> --
> Regards,
> Jay Freedman
> Microsoft Word MVP FAQ: http://word.mvps.org
>