application.Documents.Add(filePath) returns null 当 VBA 代码干扰时
application.Documents.Add(filePath) returns null when VBA code interfering
我们的产品使用 VSTO (C#) 从模板创建新文档:
Document document =_application.Documents.Add(filePath);
'document' 变量将包含对文档对象的引用。
现在我们有一个客户在 Word 启动文件夹中安装了一个模板,其中包含 VBA 创建文档的代码,使用该文档并将其删除。
'' Module contents
Dim oAppClass As New ThisApplication
Public Sub AutoExec()
Set oAppClass.oApp = Word.Application
End Sub
'' Class module contents
Public WithEvents oApp As Word.Application
Private Sub oApp_NewDocument(ByVal Doc As Document)
Dim oDoc As Document
Set oDoc = Documents.Add
' do something with the document
oDoc.Close
End Sub
当此 vba 代码就位时,C# 代码(在问题的顶部)return null 而不是刚刚创建的文档。所以该文档实际上是在 Word 中创建的,并且 application.Documents 集合包含一个额外的文档,但是 'document' 变量为空。
我正在寻找一个合适的解决方案来获取对新创建文档的引用。
我可以在添加新文档之前获取当前打开的文档列表,然后获取列表,比较它们并找到新文档。但是如果 VBA 代码创建了一个新文档而不关闭它,就会有 2 个新文档。我仍然不知道我从 C# 代码创建的文档是什么。
在这种情况下,有没有办法确定我从 C# 代码创建的文档?
"is there a way of determining what document I created from C# code in this situation?"
是的。查询文档的AttachedTemplate
属性。如果启动模板中的 VBA 代码与您的问题中显示的一样,它创建的任何文档 .AttachedTemplate.Name
将 return Normal.dotm
,而您的文档将附加到您作为 filePath
.
传入的模板
通过比较 .AttachedTemplate.FullName
和 filePath
你应该得到一个匹配。
我们的产品使用 VSTO (C#) 从模板创建新文档:
Document document =_application.Documents.Add(filePath);
'document' 变量将包含对文档对象的引用。 现在我们有一个客户在 Word 启动文件夹中安装了一个模板,其中包含 VBA 创建文档的代码,使用该文档并将其删除。
'' Module contents
Dim oAppClass As New ThisApplication
Public Sub AutoExec()
Set oAppClass.oApp = Word.Application
End Sub
'' Class module contents
Public WithEvents oApp As Word.Application
Private Sub oApp_NewDocument(ByVal Doc As Document)
Dim oDoc As Document
Set oDoc = Documents.Add
' do something with the document
oDoc.Close
End Sub
当此 vba 代码就位时,C# 代码(在问题的顶部)return null 而不是刚刚创建的文档。所以该文档实际上是在 Word 中创建的,并且 application.Documents 集合包含一个额外的文档,但是 'document' 变量为空。
我正在寻找一个合适的解决方案来获取对新创建文档的引用。
我可以在添加新文档之前获取当前打开的文档列表,然后获取列表,比较它们并找到新文档。但是如果 VBA 代码创建了一个新文档而不关闭它,就会有 2 个新文档。我仍然不知道我从 C# 代码创建的文档是什么。
在这种情况下,有没有办法确定我从 C# 代码创建的文档?
"is there a way of determining what document I created from C# code in this situation?"
是的。查询文档的AttachedTemplate
属性。如果启动模板中的 VBA 代码与您的问题中显示的一样,它创建的任何文档 .AttachedTemplate.Name
将 return Normal.dotm
,而您的文档将附加到您作为 filePath
.
通过比较 .AttachedTemplate.FullName
和 filePath
你应该得到一个匹配。