none
In Word VBA - Determine if active selection is part of a Bookmark RRS feed

  • Question

  • Hello fellow developers!

    I have a large document with dozens of bookmarks. At any given point I might be somewhere in my document -maybe in a bookmark's range, or maybe not. I like to identify IF I am standing in the middle of bookmark. If I open the Insert-->Links-->Bookmark dialog box it already identifies IF I am in a bookmark and it selects this bookmark, other wise it selects the first one.

    That is exactly what I want to do; when I run my macro or process it will know that I am in 'xyz' bookmark. If not it will do nothing.

    Any ideas as to how can I achieve that?


    Gustavo Miller

    Tuesday, June 9, 2015 2:21 PM

All replies

  • Here are two functions you can use:

    Function GetRangeBookmark(rng As Range) As String
        If rng.Bookmarks.Count > 0 Then
            GetRangeBookmark = rng.Bookmarks(1).Name
        End If
    End Function
    
    Function GetSelectionBookmark() As String
        GetSelectionBookmark = GetRangeBookmark(Selection.Range)
    End Function

    The first is more general; you can specify any range (whether selected or not) as argument.

    The second will return the name of the first bookmark found within the current selection, or an empty string if there are no bookmarks within (i.e. overlapping) the selection.


    Regards, Hans Vogelaar (http://www.eileenslounge.com)

    Friday, June 12, 2015 8:09 PM
  • While Hans's functions will tell you if there is a bookmark in the range, the following will tell you if the range is in a bookmark or which bookmark, however if you are running a process, wouldn't it be better to set the range to the bookmark you want to process? See the FillBM function on my web site at http://www.gmayor.com/useful_vba_functions.htm

    Sub Macro1()
        MsgBox IsBookmark(Selection.Range) & vbCr & _
        InWhichBookmark(Selection.Range)
    End Sub
    
    Function IsBookmark(oRng As Range) As Boolean
    Dim oBM As Bookmark
        For Each oBM In ActiveDocument.Bookmarks
            If oRng.InRange(oBM.Range) Then
                IsBookmark = True
                Exit For
            End If
        Next oBM
    lbl_Exit:
        Exit Function
    End Function
    
    Function InWhichBookmark(oRng As Range) As String
    Dim oBM As Bookmark
    Dim bBM As Boolean
        For Each oBM In ActiveDocument.Bookmarks
            If oRng.InRange(oBM.Range) Then
                InWhichBookmark = oBM.name
                bBM = True
                Exit For
            End If
        Next oBM
        If Not bBM Then
            InWhichBookmark = "Not in a bookmark"
        End If
    lbl_Exit:
        Exit Function
    End Function


    Graham Mayor - Word MVP
    www.gmayor.com

    Saturday, June 13, 2015 7:28 AM