tell application "Finder"
set input to selection
end tell
tell application id "com.microsoft.Word"
activate
set view type of view of active window to draft view
repeat with aFile in input
open aFile
set theOutputPath to ((aFile as text) & ".pdf")
repeat while not (active document is not missing value)
delay 0.5
end repeat
set activeDoc to active document
save as activeDoc file name theOutputPath file format format PDF
close active document saving no
end repeat
end tell
With Ms Word for Mac Version 16.70 I get this error message:
error "Microsoft Word got an error: active document doesn’t understand the “save as” message." number -1708 from active document
tell application "Finder"
set input to selection
end tell
tell application id "com.microsoft.Word"
activate
set view type of view of active window to draft view
repeat with aFile in input
open aFile
set theOutputPath to ((aFile as text) & ".pdf")
repeat while not (active document is not missing value)
delay 0.2
end repeat
set activeDoc to active document
save activeDoc in theOutputPath as format PDF
close active document saving no
end repeat
end tell
The problem is not with the save as command but with the repeat loop.
[I added a line to get rid of the double extension.]
tell application "Finder"
set input to selection
end tell
tell application id "com.microsoft.Word"
activate
repeat with aFile in input
set aFile to (aFile as string)
open aFile
repeat until full name of active document = aFile
delay 0.1
end repeat
set aDest to (text 1 thru -6 of aFile) & ".pdf" -- assuming extension is always '.docx'
save as active document file name aDest file format format PDF
close active document saving no
end repeat
end tell
I modified the code to verify the selection only has “docx” files
tell application "Finder"
set input to selection
set c to 1
repeat with i from 1 to count input
set item i of input to {text 1 thru -6 of (item i of input as text), "." & name extension of item i of input}
if item 2 of item i of input ≠ ".docx" then -- move files that are not 'docx' to front of list
if i > 1 then
set tmp to item i of input
set item i of input to item c of input
set item c of input to tmp
end if
set c to c + 1
end if
end repeat
end tell
set input to items c thru -1 of input -- should now only be docx files
tell application id "com.microsoft.Word"
activate
set view type of view of active window to draft view
repeat with aFile in input
set theOutputPath to item 1 of aFile
open file (theOutputPath & item 2 of aFile)
set theOutputPath to theOutputPath & ".pdf"
repeat while active document is missing value
delay 0.5
end repeat
set activeDoc to active document
save as activeDoc file name theOutputPath file format format PDF
close active document saving no
end repeat
end tell