Error in COM Word object when using a relative path to add a picture

Get help with using AutoHotkey (v2 or newer) and its commands and hotkeys
hisrRB57
Posts: 69
Joined: 13 Jan 2019, 11:43

Error in COM Word object when using a relative path to add a picture

04 May 2024, 08:12

I have the follwoing code:

Code: Select all

#Requires AutoHotkey v2.1-a
#SingleInstance Force

xrelPath := ".\media\MonaLisa.jpg"
xFullPath := A_Scriptdir . "\media\Monalisa.jpg"

; Open Word Document
oWord := ComObject("Word.Application")
oWord.Visible := true
oWord.Activate
WinWaitActive "ahk_class OpusApp",,2
oDoc := oWord.Documents.Add()
Sleep 500

; Upload Picture to Word with fullpath
xNextPar := 0
oDoc.Paragraphs.item(++xNextPar).range.InsertParagraphAfter()
oAfbeelding := oDoc.Paragraphs.item(xNextPar).range.InlineShapes.AddPicture(xFullPath)

; Upload Picture to Word with relative path
oDoc.Paragraphs.item(++xNextPar).range.InsertParagraphAfter()
oAfbeelding := oDoc.Paragraphs.item(xNextPar).range.InlineShapes.AddPicture(xRelPath)

The first load of the picture with the full path goes weel, but the second upload with the relative path fails wit the error:

Image

Now in this case it is not a big issue because the picture can be stored in the document. But when you use shortcutes to documents your document is no longer portable when you use the fullpath.
Anybody an idea?
Attachments
Error.jpg
Error.jpg (70.85 KiB) Viewed 345 times
User avatar
gregster
Posts: 9224
Joined: 30 Sep 2013, 06:48

Re: Error in COM Word object when using a relative path to add a picture

05 May 2024, 02:18

The dot in the file path looks wrong: xrelPath := ".\media\MonaLisa.jpg"
What's the plan here? I don't think that a single . can be a valid name for a folder in Windows.
User avatar
boiler
Posts: 17706
Joined: 21 Dec 2014, 02:44

Re: Error in COM Word object when using a relative path to add a picture

05 May 2024, 06:22

Actually, a single dot indicates the current directory, so these are equivalent for identifying the relative path:

Code: Select all

xrelPath := "[c].\media\MonaLisa.jpg[/c]"
xrelPath := "media\MonaLisa.jpg"
So if the working directory is the script directory, and A_Scriptdir . "\media\Monalisa.jpg" is valid for the full path, then .\media\MonaLisa.jpg is a valid relative path. There is some discussion on that here.

I think the issue is that just because the script directory is AHK's working directory, it doesn't follow that the COM object sees the script directory as the current directory, so identifying a relative path assuming the script directory is its current directory will result in it not finding the file.

Return to “Ask for Help (v2)”

Who is online

Users browsing this forum: DavidP and 93 guests