Reputation: 393
When using Word for Mac 2011 and Tools
→ Macro
→ Record New Macro
to record a VBA macro for inserting a picture via Insert
→ Photo
→ Picture from File
the picture will be inserted in your document during recording, but you will end up with a non-functional macro like this one:
Sub NotWorkin()
'
' NotWorkin Visual Basic for Applications Macro
'
'
Selection.InlineShapes.AddPicture fileName:= _
"/Users/mark/SMPTE_RP_219_2002.png", LinkToFile:=False, SaveWithDocument _
:=True
Selection.InlineShapes.AddPicture fileName:="", LinkToFile:=False, _
SaveWithDocument:=True
End Sub
When you try to run the macro it will throw an error:
Run-time error '5152':
This is not a valid file name.
Try one or more of the following:
* Check the path to make sure it was typed correctly.
* Select a file from the list of files and folders.
This was tested with OS X (Version 10.8.5) and Microsoft® Word for Mac 2011, Version 14.4.3 (140616), Latest Installed Update: 14.4.3
What is happening here and why is the macro not working ?
Upvotes: 0
Views: 2278
Reputation: 393
It seems the macro recorder generates quite buggy code in this case. It inserts two code blocks where the second one has an empty file name, the complete second block can be deleted :
Selection.InlineShapes.AddPicture fileName:="", LinkToFile:=False, _
SaveWithDocument:=True
Then there is a nasty bug in the macro recorder leading to slashes instead of colons in the string for fileName in the first code block:
"/Users/mark/SMPTE_RP_219_2002.png"
where the correct format for Word for Mac 2011 on OS X has to be:
"Users:mark:SMPTE_RP_219_2002.png"
A working code would here be:
Sub Workin()
'
' Workin Visual Basic for Applications Macro
'
'
Selection.InlineShapes.AddPicture fileName:= _
"Users:mark:SMPTE_RP_219_2002.png", LinkToFile:=False, SaveWithDocument _
:=True
End Sub
If you link to the pictures instead of embedding them and then use VBA to get the paths of all linked images in a document, the path strings will also be formatted using slashes instead of colons:
Sub DebugPrintInlineImageNames()
On Error Resume Next
For Each InlineShape In ActiveDocument.InlineShapes
Debug.Print (InlineShape.LinkFormat.SourceFullName)
Next InlineShape
These strings have to be converted so that VBA can find the files, simplest example:
ILpath = "/Users/mark/SMPTE_RP_219_2002.png" ' example path
Colpath = Replace(ILpath, "/", ":") ' replace all slashes by colons
FixPath = Mid(Colpath, 2, Len(Colpath) - 1) ' remove fist char, ie prefixed colon
Thus, if you receive a Run-time error '5152': This is not a valid file name
, make sure your file name is formatted correctly: colons instead of slashes for Office 2011 on OS X
Upvotes: 2