从Excel VBA编辑器中获取已打开的Word文档的名称

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

Hello StackOverflow社区。我有一个简单的问题4你们。

我打开了一个.xlsm工作簿和一个.docx文档。我正在编写的代码是Excel vba编辑器中的VBA。

[从那里我想在MsgBox中显示当前打开的Word文件名。我的主要问题是从Excel VBA编辑器引用已打开的Word文档。我在https://excel-macro.tutorialhorizon.com/vba-excel-get-the-instance-of-already-opened-word-document/处找到了此代码,但是在重写后,出现了以下错误:activex组件无法创建对象429。

Sub Get_Opened_Doc_Instance()
           'Variables declaration
           'Dim WordApp As Object
            Dim WordApp As Word.Application
           'Dim WordDoc As Object
            Dim WordDoc As Word.Document
           'Dim Text As String             
           'this variable is here because later I'm going to search this file.
                Set WordApp = GetObject(, Word.Application)
               'Set WordDoc = GetObject(, Word.Document)
                WordApp.Visible = True          'this line or the next one returns the error
                                                'activex component can't create object 429
    MsgBox WordApp.ActiveDocument.Name
End Sub

我是VBA的新手,所以如果我出错了,请原谅。

My Excel VBA编辑器工具->参考下面的屏幕快照。enter image description here

excel vba automation office365 word
1个回答
0
投票

您在上面的宏中不需要前两行-仅需这三行即可获得所需的内容:

Set objWord = GetObject(, "Word.Application")

objWord.Visible = True

MsgBox objWord.ActiveDocument.Name
© www.soinside.com 2019 - 2024. All rights reserved.