Bookmark deleted - generates error

R

Ronny

In my macro I identify a chapter and delete it. To identify the chapter I use
a bookmark.
This code runs every time the doc is opened. When the document is opened the
second time I get an error because the bookmark is missing. Is there a way to
avoid this problem?
Perhaps there is a way to detect if the bookmark exists?
 
J

Jean-Guy Marcil

Ronny said:
In my macro I identify a chapter and delete it. To identify the chapter I use
a bookmark.
This code runs every time the doc is opened. When the document is opened the
second time I get an error because the bookmark is missing. Is there a way to
avoid this problem?
Perhaps there is a way to detect if the bookmark exists?

Yes, there is:

If ActiveDocument.Bookmarks.Exists("myBookMark") Then
'Delete
Else
'Do something else?
End If
 
G

Gordon Bentley-Mix

Ronny,

Something like this should work:

Sub DeleteBookmark1()
If ActiveDocument.Bookmarks.Exists("Bookmark1") Then
ActiveDocument.Bookmarks("Bookmark1").Range.Delete
End If
End Sub

Note that if you do this frequently throughout your template you may want to
write a procedure that accepts arguments for the bookmark name and call it
whenever you need to. The structure would look like this:

Sub DeleteBookmark(BookmarkName As String)
If ActiveDocument.Bookmarks.Exists(BookmarkName) Then
ActiveDocument.Bookmarks(BookmarkName).Range.Delete
End If
End Sub

And a call to it would look like this:

DeleteBookmark "Bookmark1"

What's important is the .Exists method for the Bookmark object. That is
where the solution to your problem lies.
--
Cheers!
Gordon

Uninvited email contact will be marked as SPAM and ignored. Please post all
follow-ups to the newsgroup.
 
G

Gordon Bentley-Mix

You're bloody quick Jean-Guy! Beat me by 5 minutes! (Although I reckon that's
'cause I can't escape my "professional trainer" roots so I couldn't help but
do more than just answer the original question. ;-D)
 
J

Jean-Guy Marcil

Gordon Bentley-Mix said:
You're bloody quick Jean-Guy! Beat me by 5 minutes! (Although I reckon that's
'cause I can't escape my "professional trainer" roots so I couldn't help but
do more than just answer the original question. ;-D)

I am not sure I like what you are implying here... was my answer less than
adequate?

:p

Indeed, your answer was very good and very thorough!
 
G

Gordon Bentley-Mix

Apparently not good enough to earn a "green tick" though. Once again, short
and sweet wins the day. ;-P
-----
Cheers!

Gordon

Uninvited email contact will be marked as SPAM and ignored. Please post all
follow-ups to the newsgroup.
 

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