Search code examples
vbams-wordbookmarks

Word VBA - check if cursor is between two bookmarks


I am working on Macro in Word (it also uses Excel, but nvm) and I need to check if cursor is currently between two specific bookmarks.

To be honest I have no idea how to approach the problem. I used google, I used stackoverflow search and found nothing on this topic. It is my first VBA for Word.

Please understand, that I do not provide any code - as I said, no idea how to try to write it and my research returned no results.


Solution

  • The following function will return False or True as a result of checking if the beginning of your selection is between 2 bookmarks passed by name to the function. It doesn't matter in which order you pass bookmarks name.

    Function BetweenBookmarks(FirstBookmarkName, SecondBookmarkName)
    
        If Selection.Start > ActiveDocument.Bookmarks(FirstBookmarkName).Range.End _
            And _
            Selection.End < ActiveDocument.Bookmarks(SecondBookmarkName).Range.Start Then
    
                BetweenBookmarks = True
    
        ElseIf Selection.Start > ActiveDocument.Bookmarks(SecondBookmarkName).Range.End _
            And _
            Selection.End < ActiveDocument.Bookmarks(FirstBookmarkName).Range.Start Then
    
                BetweenBookmarks = True
        Else
    
                BetweenBookmarks = False
        End If
    End Function
    

    Function can be called in this way:

    Debug.Print BetweenBookmarks("First", "Second")
    Debug.Print BetweenBookmarks("Second", "First")
    

    You could make some other modification on your own by changing .End and .Start properties within the function.