Delete bookmark if it contains specific words

A

aehan

Hello all

I have some code which is supposed to delete data if it contains specific
words. The code I have is as follows:

If ActiveDocument.Bookmarks("test").Range.Words(2) = "Central
Service" Then
With Selection
.GoTo What:=wdGoToBookmark, Name:="test"
.Delete
.GoTo What:=wdGoToBookmark, Name:="test2"
.MoveRight unit:=wdWord, Count:=4, Extend:=wdExtend
.Delete
End With
End If

I have stepped through the code and it fails at the IF clause, so doesn't
run. If, however, I only had one word in the bookmark and amended the if to
read:

If ActiveDocument.Bookmarks("test").Range.Words(1) = "Central" Then
With Selection
.GoTo What:=wdGoToBookmark, Name:="test"
.Delete
.GoTo What:=wdGoToBookmark, Name:="test2"
.MoveRight unit:=wdWord, Count:=4, Extend:=wdExtend
.Delete
End With
End If

the code runs beautifully. I really need to use the two word option, and I
have spent ages trying to work out why it doesn't work when looking for two
words. Can anyone help me and tell me what I've done wrong please?

Thanks in frustration
Aehan
 
J

Jay Freedman

The expression .Words(2) means specifically "the word that is in the
second position in the bookmark's range". It cannot refer to two
words. If indeed "Central" is the second word in the range, then
"Service" could be the third word, or .Words(3).

I think the code you showed (which is obviously slightly modified from
macro recorder output) is far too specific about what it expects to
find in the bookmark, while at the same time being very inefficient.
If you just want to know whether the words "Central Service" are
_somewhere_ within the bookmark, and if they are then delete the whole
bookmark as well as the bookmark "test2", then all you need is this:

With ActiveDocument.Bookmarks("test").Range
If InStr(.Text, "Central Service") Then
.Delete
ActiveDocument.Bookmarks("test2").Range.Delete
End If
End With

This code doesn't have to move the cursor in the document.
 
A

aehan

Hi Jay

Thank you very much, I've spent a whole afternoon and into this evening
trying to find a way of making this work. As you guessed, I'm not too good
at this and tend to use the recorder, but I'm learning. I really appreciate
your help.

Thanks
Aehan
 

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