[Last Call] Learn how to a build a cloud-first strategyRegister Now

x
  • Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 1515
  • Last Modified:

VBA - Word 2003: Create a Style if None Exists.

Hi There,

We've set up our templates to use a style called "DocID".  In older docs, it was a character style, in the new ones: paragraph.  We also have docs that do not have the style at all.

We want to shoot for consistency.

I'm trying to write a macro that will create the DocID paragraph style if none exists.  If the style name is in the collection, I want to delete it and add the new paragraph style.  

Unfortunately, my error handler doesn't seem to be working.  I suspect I'm using the wrong one, or I have it in the wrong location.  

If the style exists, I get run time error 5173.  "Style name already exists or is reserved for a built-in style."

Here's the code I'm trying:

On Error GoTo ErrSTYLE_NAME  
    Set MyStyle = ActiveDocument.Styles.Add(Name:="DocID", _
        Type:=wdStyleTypeParagraph)
    With MyStyle.Font
        .Size = 7
    End With
    With MyStyle.ParagraphFormat
        .SpaceBefore = 6
        .Alignment = wdAlignParagraphLeft
    End With
        GoSub NDV

ErrSTYLE_NAME
    ActiveDocument.Styles("DocID").Delete

Any suggestions?

THANKS!
0
jtaylerg
Asked:
jtaylerg
  • 2
1 Solution
 
GrahamSkanCommented:
You could write a function to check it the style exists. You won't need to rely on error trapping.

Function StyleExists(strName As String, Doc As Document) As Boolean
    Dim sty As Style
   
    For Each sty In ActiveDocument.Styles
        If LCase$(strName) = LCase$(sty.NameLocal) Then
            StyleExists = True
            Exit Function
        End If
    Next sty
End Function

0
 
jtaylergAuthor Commented:
Thank you so very much.

It's been such a hectic week -- I haven't had a chance to follow up.

Thanks -- JTG

0
 
GrahamSkanCommented:
OK. Thanks and good luck.
0

Featured Post

Hire Technology Freelancers with Gigs

Work with freelancers specializing in everything from database administration to programming, who have proven themselves as experts in their field. Hire the best, collaborate easily, pay securely, and get projects done right.

  • 2
Tackle projects and never again get stuck behind a technical roadblock.
Join Now