0
votes

Is it possible to search the content inside a bookmark and if it exists, do something.

For example, if there is a word document with a bookmark named Bookmark1. The enclosing text for Bookmark1 was created by highlighting the the text "Entered Text Goes Here". I want to create a macro that will check to see if the text inside the bookmark was changed, and if NOT, delete the text, the bookmark, the section break before it.

The code below does this except that it deletes the bookmark even if the text is different because it is looking for the name of the bookmark, not its content.

If ActiveDocument.Bookmarks.Exists("Bookmark1") = True Then
    ActiveDocument.Bookmarks("Bookmark1").Select
    Selection.Delete
    With Selection
        .EndKey Unit:=wdStory
        .TypeBackspace
        .Delete
    End With
End If

I really want the If statement to say something like: If the text inside the Bookmark1 = "Entered Text Goes Here" Then do all the stuff below, else quit.

Ideas anyone?

Word 2007.

1
Try something like If ActiveDocument.Bookmarks("Bookmark1").range = "Entered Text Goes Here" then...Kazimierz Jawor

1 Answers

0
votes

The below should work if your document is set up how I think it is, otherwise you will need to have a play around with it:

'TestTxt is the default text in the bookmark (assuming that you are not including the paragraph mark in the bookmark)
Dim TestTxt As String: TestTxt = "Enter text here"
'DMRng is the range of the the bookmark you are looking at
Dim BMRng As Range: Set BMRng = ThisDocument.Bookmarks("Bookmark1").Range


If BMRng.Text = TestTxt Then
        'Start is the beginning of the bookmark - 1 (as the character before hand should be your section break?!)
        BMRng.SetRange Start:=BMRng.Start - 1, End:=BMRng.End
        BMRng.Delete
End If