从 Microsoft Excel 打开特定的 Word 文档

问题描述 投票:0回答:1

我正在尝试从 Microsoft Excel 打开特定的 Word 文档。我有以下代码:

    Dim WordApp As Object, WordDoc As Object, FileToOpen As String

Sub Generate_Report()

FileToOpen = "C:\Users\david\resource letter.docx"
Set WordApp = CreateObject("Word.Application")
Set WordDoc = WordApp.Documents.Open(FileToOpen)
WordApp.Visible = True

End Sub

但是当我运行代码时,它在 Set WordDoc = WordAppDocuments.Open(FiletoOpen) 行上失败,表示我缺少一个对象。

我尝试过使用documentsopen功能。我尝试向它提供文档或文件类型而不是字符串。我之前确保了对象的名称是对齐的,因此至少在理论上单词文档应该是单词应用程序的对象。另外,已尝试将语法更改为

Set WordDoc = WordApp.Documents.Open Filename =: "C:\Users\david\resource letter.docx" 

但 VBA 将其作为语法错误抛出(不知道为什么)。救命!

excel vba ms-word
1个回答
0
投票

此代码对我有用:

首先,请确保您已通过“工具”->“参考”引用了“Microsoft Word 16.0 对象库”

Sub OpenDoc()
    Dim strFile As String

    strFile = "C:\Users\LIUIO\OneDrive - LANXESS Deutschland GmbH\Dokumente\Macro Files\USERFORM.docx"    'change to path of your file
    If Dir(strFile) <> "" Then    'to check if document exists at the given location
        Documents.Open strFile
    End If
End Sub
© www.soinside.com 2019 - 2024. All rights reserved.