让我们再试一次......
然后创建另一个加载项(我将给出一个 XLAM 的示例),或者您可以将您的 COM 加载项修改为此,或者确保这个新加载项正在运行。此插件将捕获应用程序级 App_WorkbookActivate 事件,并检查新工作簿名称是否可能来自 Microsoft Word。
如果工作簿符合此条件,因为它正在触发 App_WorkbookActivate 事件,那么假设 MS Word 中的当前 ActiveDocument 是容器似乎相当安全。
然后,我们只需设置一些对象变量来捕获Word.Application,然后只需获取ActiveDocument,它是.Path,它是.Name,我们可以将这些值存储在命名变量中Excel 工作簿。
您可以在Names 管理器中查看它们,或者通过引用它们的名称.Names("docPath") 和.Names("docName") 以编程方式访问它们。
将其放入 XLAM 文件中的标准模块中:
Sub Auto_Open()
Application.Run "ThisWorkbook.Workbook_Open" 'just in case
End Sub
以下代码位于 XLAM 文件的 ThisWorkbook 模块中:
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