让我们再试一次...
然后创建另一个加载项(我将给出一个 XLAM 的示例),或者您可以将您的 COM 加载项修改为此,或确保此新加载项正在运行。此插件将捕获应用程序级App_WorkbookActivate
事件,并检查新工作簿名称以查看它是否可能来自 Microsoft Word。
如果工作簿符合这个标准,因为它正在触发事件,那么假设MS Word 中的当前是容器App_WorkbookActivate
似乎是相当安全的。ActiveDocument
然后,我们只需设置一些对象变量来捕获Word.Application
,然后只需获取ActiveDocument
、it's.Path
和 it's .Name
,我们可以将这些值存储在 Excel 工作簿中的命名变量中。
您可以在Names
管理器中查看它们,或通过引用它们的名称以编程方式访问它们,.Names("docPath")
并且.Names("docName")
.
将其放入 XLAM 文件中的标准模块中:
Sub Auto_Open()
Application.Run "ThisWorkbook.Workbook_Open" 'just in case
End Sub
以下代码位于ThisWorkbook
XLAM 文件的模块中:
Option Explicit
Private WithEvents App As Application
Dim dictWorkbooks As Object
Private Sub Workbook_Open()
'## Instantiate the public variables for this Add-in:
Set App = Application
Set dictWorkbooks = CreateObject("Scripting.Dictionary")
End Sub
Private Sub App_WorkbookActivate(ByVal Wb As Workbook)
'## Attempt to determine if a Workbook is opened from MS Word,
' and if so, store the container document's path & name in
' named variable/range in the Workbook.
Dim wdApp As Object
Dim wdDoc As Object
Dim docPath As String
Dim docName As String
Dim w As Integer
If Wb.Name Like "Chart in Microsoft Word" Then
'Get out of here if we already have this workbook activated.
If dictWorkbooks.Exists(Wb.Name) Then Exit Sub
Set wdApp = GetObject(, "Word.Application")
Set wdDoc = wdApp.ActiveDocument
docPath = wdDoc.Path
docName = wdDoc.Name
dictWorkbooks.Add Wb.Name, docName
With Wb
On Error Resume Next
.Names("docPath").Delete
.Names("docName").Delete
On Error GoTo 0
.Names.Add Name:="docPath", RefersToR1C1:=docPath
.Names("docPath").Comment = "A variable stores the parent DOC file's path"
.Names.Add Name:="docName", RefersToR1C1:=docName
.Names("docName").Comment = "A variable stores the parent DOC file's name"
End With
End If
End Sub
Private Sub App_WorkbookBeforeClose(ByVal Wb As Workbook, Cancel As Boolean)
'## If you open multiple charts from the word document, without closing the Workbook
' they will be assigned unique names. However, if you open & close multiple Workbook
' they will all have the same name "Chart in Microsoft Word". This method will
' remove an existing Key from our Dictionary when a workbook is closed, in order to
' prevent false matches.
If dictWorkbooks.Exists(Wb.Name) Then _
dictWorkbooks.Remove Wb.Name
End Sub