VBA to delete everything before a given hidden bookmark

E

Enda

Hi,
I would appreciate help with the following.

I have a hidden bookmark in a document. I wish to delete all content
in the document up that bookmark.

The code I started with is below. It throws an error '5904 Cannot edit
range'. This might be when it reaches a table or a field. Cannot
anyone suggest improvements?

Thanks,
Enda

'******************************************************************
' Removes all text up to a given bookmark. Does not save the
' altered document.
'
' bmark - the bookmark up to which everything is deleted
' doc - the document to operate on
'******************************************************************
Public Sub removeBeforeBookmark(bmark As Bookmark, doc As Document)


On Error GoTo ErrHandler

Dim para As Paragraph
Dim nextPar As Paragraph

Set para = doc.Paragraphs.First

Do Until para.Range.Bookmarks.Exists(bmark.Name) = True

Set nextPar = para.Next
para.Range.Delete

Set para = nextPar

Loop

Exit Sub

ErrHandler:
Dim routine As String
routine = "removeBeforeBookmark "

Select Case Err.Number

'Cannot Edit range
'Case 5904


Case Else
MsgBox routine _
& vbNewLine & Error(Err) _
& vbNewLine & Err.Number _
& vbNewLine & Err.Description _
& vbNewLine & Err.Source
End Select

End Sub
 
H

Helmut Weber

Hi Enda,
how about this quick one?
---
Dim r As Range
Set r = Selection.Range
r.Start = 0
r.End = ActiveDocument.Bookmarks("M9").Range.Start
r.Delete
---
One could even pack everything in one line,
but that's a matter of taste.
Do you still get the error?
Greetings from Bavaria, Germany
Helmut Weber, MVP
"red.sys" & chr(64) & "t-online.de"
Word XP, Win 98
 
J

Jonathan West

Helmut Weber said:
Hi Enda,
how about this quick one?
---
Dim r As Range
Set r = Selection.Range
r.Start = 0
r.End = ActiveDocument.Bookmarks("M9").Range.Start
r.Delete

Yup, like this :)

ActiveDocument.Range(0, ActiveDocument.Bookmarks("M9").Range.Start).Delete
 

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