Page 1 of 1

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

Posted: 04 May 2024, 08:12
by hisrRB57
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?

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

Posted: 05 May 2024, 02:18
by gregster
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.

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

Posted: 05 May 2024, 06:22
by boiler
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.