简体   繁体   English

使用 Excel VBA 保存 Word 文档时出现路径错误 5152

[英]Path error 5152 when saving Word document using Excel VBA

Language version: Microsoft Word/Excel version 16.41语言版本:Microsoft Word/Excel 版本 16.41
Operating system: Mac OS Mojave 10.14.6操作系统:Mac OS Mojave 10.14.6

I am trying to use Excel VBA to save a Word document on my desktop.我正在尝试使用 Excel VBA 在我的桌面上保存 Word 文档。

Result:结果:

Run time error 5152. This is not a valid file name.运行时错误 5152。这不是有效的文件名。 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 - 从文件和文件夹列表中选择一个文件

I am using Microsoft Excel version 2008 and Microsoft Word version 2008. I am using early binding and I have selected Microsoft Excel, Office, and Word 16.0 Object Library.我使用的是 Microsoft Excel 2008 版和 Microsoft Word 2008 版。我使用的是早期绑定并且我选择了 Microsoft Excel、Office 和 Word 16.0 对象库。 (Does the 16.0 object library seem odd for version 2008?) (Windows 10 Pro version 2004. Microsoft Office 365 Subscription) (对于 2008 版,16.0 对象库是否看起来很奇怪?)(Windows 10 专业版 2004 版。Microsoft Office 365 订阅)

I am trying to follow this tutorial .我正在尝试按照本教程进行操作

Line with error:有错误的行:

.ActiveDocument.SaveAs2 Environ("UserProfile") & "\Desktop\MovieReport.docx"

My code :我的代码:

Option Explicit

Sub CreateBasicWordReportEarlyBinding()

    Dim wdApp As Word.Application

    Set wdApp = New Word.Application
    With wdApp

        .Visible = True
        .Activate
        .Documents.Add
       
        With .Selection
            .ParagraphFormat.Alignment = wdAlignParagraphCenter
            .BoldRun
            .Font.Size = 18
            .TypeText "Best Movies Ever"
            .BoldRun
            .Font.Size = 12
            .TypeText vbNewLine
            .ParagraphFormat.Alignment = wdAlignParagraphLeft
            .TypeParagraph
        End With

        Range("A2", Range("A2").End(xlDown).End(xlToRight)).Copy
        .Selection.Paste            
        .ActiveDocument.SaveAs2 Environ("UserProfile") & "\Desktop\MovieReport.docx"
        .ActiveDocument.Close
        .Quit
    End With

   'Set wdApp = Nothing
End Sub

You must use "ActiveDocument.SaveAs", not "ActiveDocument.SaveAs2".您必须使用“ActiveDocument.SaveAs”,而不是“ActiveDocument.SaveAs2”。 You cannot use "ActiveDocument.SaveAs2" method if you use Office 2010 or an older version.如果您使用 Office 2010 或更旧版本,则不能使用“ActiveDocument.SaveAs2”方法。 Use the following code and I hope your problem will be solved.使用以下代码,希望您的问题得到解决。

With wdApp  
   
   'Your codes...

   SaveName = Environ("UserProfile") & "\Desktop\MovieReport.docx"

   If .Version <= 12 Then
      .ActiveDocument.SaveAs SaveName
   Else
      .ActiveDocument.SaveAs2 SaveName
   End If
   
End With

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM