【问题标题】:How to use VBA in Word for Mac 2011 to insert images without run-time error 5152如何在 Word for Mac 2011 中使用 VBA 插入图像而不会出现运行时错误 5152
【发布时间】:2014-07-29 19:59:36
【问题描述】:

当使用 Word for Mac 2011 和 ToolsMacroRecord New Macro 录制用于插入图片的 VBA 宏时,通过 InsertPhotoPicture from File 图片将插入到您的文档中在录制过程中,但你最终会得到一个像这样的非功能宏:

 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

当你尝试运行宏时,它会抛出一个错误:

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.

这是在 OS X(版本 10.8.5)和 Microsoft® Word for Mac 2011, 版本 14.4.3 (140616), 最新安装的更新:14.4.3


这里发生了什么,为什么宏不起作用?

【问题讨论】:

    标签: macos vba ms-office ms-word


    【解决方案1】:

    在这种情况下,宏记录器似乎生成了相当多的错误代码。它插入两个代码块,其中第二个具有空文件名,可以删除完整的第二个块:

    罢工>

    Selection.InlineShapes.AddPicture fileName:="", LinkToFile:=False, _
        SaveWithDocument:=True
    

    然后在宏记录器中存在一个令人讨厌的错误,导致第一个代码块中 fileName 的字符串中出现斜杠而不是冒号:
    "/Users/mark/SMPTE_RP_219_2002.png"
    OS X 上 Word for Mac 2011 的正确格式必须是:
    "Users:mark:SMPTE_RP_219_2002.png"

    这里的工作代码是:

     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
    

    如果您链接到图片而不是嵌入它们,然后使用 VBA 获取文档中所有链接图像的路径,则路径字符串也将使用斜杠而不是冒号进行格式化:

    Sub DebugPrintInlineImageNames()
    
    On Error Resume Next
    For Each InlineShape In ActiveDocument.InlineShapes
    
            Debug.Print (InlineShape.LinkFormat.SourceFullName)
    
    Next InlineShape
    

    必须转换这些字符串,以便 VBA 可以找到文件,最简单的例子:

    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
    

    因此,如果您收到 Run-time error '5152': This is not a valid file name,请确保您的文件名格式正确:OS X 上的 Office 2011 使用冒号而不是斜线

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多