I have finally figured out how to insert a Word document in to another Word document using AppleScript, but the code below adds it at the beginning of the document instead of the end (assuming, of course, that there is text in the receiving document to begin with).

on AddAttachmentFileToWordDoc(FilePath)
    tell application "Microsoft Word"
        set ContTemp to content of text object
        set StartRange to (count of ContTemp) - 1
        set endrange to StartRange
        set theRange to create range start StartRange end endrange
        tell theRange
            insert file at end file name (FilePath as text)
        end tell
    end tell
end AddAttachmentFileToWordDoc

Can anyone please tell me how to add the document to the end of the document instead? What am I doing wrong?

up vote 2 down vote accepted
+50

Use the end of content property the get the end position of the text object.

Here's the script, tested on Microsoft Word Version 16.13

set FilePath to choose file
my AddAttachmentFileToWordDoc(FilePath)

on AddAttachmentFileToWordDoc(FilePath)
    set f to FilePath as text
    tell application "Microsoft Word"
        set StartRange to (end of content of text object of active document) - 1
        set theRange to create range (active document) start StartRange end StartRange
        insert file at after theRange file name f with confirm conversions
    end tell
end AddAttachmentFileToWordDoc

An alternative to a range, you can use after last character of active document, like this

on AddAttachmentFileToWordDoc(FilePath)
    set f to FilePath as text
    tell application "Microsoft Word"
        insert file at (after last character of active document) file name f with confirm conversions
    end tell
end AddAttachmentFileToWordDoc
  • The first method to get the range added it again, to the beginning of the document (but for a graphic file, it adds it to the end). The second method generated this error: "Microsoft Word got an error: text range id «data iWrgBB1C0000BB1C0000» of active document doesn’t understand the “insert file” message." – MBUST May 18 at 4:23
  • Solved it! Thanks! – MBUST May 18 at 4:38

Your Answer

 

By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.

Not the answer you're looking for? Browse other questions tagged or ask your own question.