PDA

View Full Version : [SOLVED:] Check if a bookmark exists within another bookmark



mortenheide
01-08-2016, 05:19 AM
Hi everybody

At my job we have several templates, within which we merge information from another system. Problem is, that this information is unusable if a user has copy-pasted text, and one bookmark has been placed within another.

So I want to create a function, that checks if a bookmark contains one or more other bookmarks.

I can of cours loop through the bookmarks in the document, and I am pretty sure that I can check within the range of a bookmark if a specific bookmark exists. But I can't seem to work with wildcards within the bookmark.exists function, so how do I determine if any bookmark exists witin a range?

Thankyou so much in advance

Morten

gmayor
01-08-2016, 06:03 AM
Maybe something like the following:
Sub Macro1()
Dim oRng As Range
Dim i As Integer, j As Integer
Dim strName As String
Set oRng = Selection.Bookmarks(1).Range
i = oRng.Bookmarks.Count
If i > 1 Then
strName = "There are " & i - 1 & " bookmarks within the bookmark " & vbCr & _
oRng.Bookmarks(1).Name & " Range." & vbCr & _
"Their names are:" & vbCr
For j = 2 To i
strName = strName & ActiveDocument.Bookmarks(j).Name
If j < i Then strName = strName & vbCr
Next j
MsgBox strName
End If
lbl_Exit:
Exit Sub
End Sub

or for a selection
Sub Macro2()
Dim oRng As Range
Dim i As Integer, j As Integer
Dim strName As String
Set oRng = Selection.Range
i = oRng.Bookmarks.Count
If i = 0 Then strName = "There are 0 bookmarks within the selected range'"
If i = 1 Then strName = "There is 1 bookmark within the selected range"
If i > 1 Then strName = "There are " & i & " bookmarks within the selected range"
If i > 0 Then
strName = strName & " named:" & vbCr
For j = 1 To i
strName = strName & ActiveDocument.Bookmarks(j).Name
If j < i Then strName = strName & vbCr
Next j
End If
MsgBox strName
lbl_Exit:
Exit Sub
End Sub


See also the FillBM function on my web site at http://www.gmayor.com/useful_vba_functions.htm

mortenheide
01-08-2016, 06:42 AM
Thankyou so much gmayor - this seems to work perfectly. Cheers