How to append the clipboard's content to a Ms Word document?

I am looking for a way to add the clipboard’s content (text only) to ~/Desktop/Extraction.docx

I don’t need to see the document while I’m appending text.

How can this be done? Thank you in advance!

macOS 14.5, Ms Word 16.87

Unless you have an alternate method of writing to the docx file, you will have to open it in Word.

use scripting additions
tell application "Microsoft Word"
	set pdt to (path to desktop as text) & "Extraction.docx"
	open pdt
	set d1 to document "Extraction.docx"
	
	-- sets the clipboard to the text of what was on the clipboard
	set theData to (the clipboard as text) -- replaces line ending with 
	set the clipboard to theData
	
	-- specifies the end of the document's text
	set tob to last character of text object of d1
	
	-- sets insertion point to after last character
	set myr to collapse range tob direction collapse end
	
	-- inserts the clipboard text to after last character
	insert text theData at end of text object of d1
		
end tell

An alternate would be to use paste object, like so. The ‘selection’ in this case is the ‘insertion point’.

	set myr to collapse range tob direction collapse end
	paste object text object of selection
2 Likes

Thank you very much. This works perfectly!

Interesting to read that it’s not possible to append to a file without opening it in Ms Word (this is possible with plain text files …).

If you don’t mind, just one other question: how can I make sure that after the clipboard insertion a new line is inserted? (So that the pasted chunks are separated by new lines.)

Thanks again!

Yes. Applescript has a write command which allows you to write directly to a text document. It is able to write the entire document or insert or append text. There are numerous posts on this site which contain examples.

Technically it is possible with a word file but one would have to either know the internal structure of a word document or have a utility that allowed such direct editing (assuming said utility was scriptable). Word of course, knows all this intimately.

In general, the easiest way to include a linefeed (or return) in a block of text is to use concatenation. If theData is a text string, then you can do something like set theData to linefeed & theData & linefeed. Then, when you insert it as above, it will add a linefeed before and after the block of text.

Using the ‘&’ allows you to concatenate bits of text (as well as coerce non-text into text) to make up a larger string.

1 Like