How to Insert Document at End of Word Doc with AppleScript

applescriptms office

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?

Best Answer

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