Search code examples
vbams-wordrangeapplescriptbookmarks

Applescript with MS Word: Creating and selecting a range using existing bookmarks


Trying to figure out how to do this via Applescript.

Here’s the code I’ve got:

tell application "Microsoft Word"

   set myRange to create range active document ¬
       start (start of content of text object of bookmark "begin_001") ¬
       end (start of content of text object of bookmark "end_001")
   select myRange

end tell

Which runs, but appears to do nothing (no selection).

I’ve double-checked that the bookmarks exist and enclose text between them.

I've found VBA code that can easily do this, but would like to stick to Applescript.

What’s the correct syntax to accomplish this?


Solution

  • One way:

    tell application "Microsoft Word"
        set myRange to (create range active document start (start of bookmark of bookmark "begin_001" of active document) end (end of bookmark of bookmark "end_001" of active document))
        select myRange
    end tell
    

    Another way:

    tell application "Microsoft Word"
        tell active document
            set myRange to (create range start (start of bookmark of bookmark "begin_001") end (end of bookmark of bookmark "end_001"))
            select myRange
        end tell
    end tell
    

    Incidentally, I would be very careful about using AppleScript to reference ranges that are not in the Main document body. AFAICR, you can do it in VBA but the things you might hope would be the equivalents in AppleScript just don't work.