xcodems-wordmacos-mojaveapplescript-objc

AppleScript insert text into Microsoft Word document


I am new to MacOS standalone application development and I am working on fixing issues in our existing application. Our application access the Microsoft Word document and perform insertion of text into the word document via AppleScript. When i am running the application and performing the insert operation via XCode, the text is not getting inserted into the Word Document. Its been working well earlier but from past few days the text is not getting inserted into Word document

The following code is being used in XCode to copy text to pasteboard and then calling the AppeScript to just insert the text into Word Document

NSPasteboard * pasteboard = [NSPasteboard generalPasteboard];
[pasteboard clearContents];
[pasteboard writeObjects:@[textToInsert]];

Following is the AppleScript being used for insertion of text into Word Document

on insertSampleText()
        try
            using terms from application "Microsoft Word"
                tell application "Microsoft Word"
                    activate
                    tell application "System Events"
                        keystroke "v" using {command down}
                    end tell
                end tell
            end using terms from
            return "0"
        on error the error_message number the error_number
            set the error_text to "" & the error_number
            return the error_text
        end try
end insertSampleText

Can you please suggest on what needs to be done in order to insert text into Word Document?


Solution

  • The line

    keystroke "v" using {command down} 
    

    won't work unless the user has enabled the Accessibility Keyboard in control panel.

    Assuming that your code is successfully running the on insertSampleText handler (personally I would put some display dialog statements in there to try to check the flow of execution) then I would start by trying something more like

    tell application "Microsoft Word"
        activate
        paste object text object of selection
    end tell
    

    but what will work may depend on exactly what you have in the clipboard and what exactly you want to happen to any existing selection

    (Although it's not obviously related to your question, if you are having trouble getting your handler code to run at all, you may find the discussion at Using AppleScript with Apple Events in macOS - Script not working helpful)