我遇到了与 this question 中的用户类似的问题.
现在我无法在下面的 Excel VBA 中将类型为“DocumentProperty”的函数变量 proDocName 设置为 wdDoc.BuiltinDocumentProperties.Item(1) 。它会抛出类型不匹配错误。
Excel VBA 子例程应首先打开 Word 实例,然后打开 Word 文档文件。
然后,我将 ByRef 文件(我在代码中将其称为 wdDoc)传递给该函数,然后在该函数中尝试获取要使用该函数写入 Excel 工作表的文档属性的值和名称。
我在 Word VBA 中测试了以下代码,它运行良好:
Sub test()
Dim wdApp As Word.Application
Dim wdDocPro As DocumentProperty
Set wdApp = GetObject(, "Word.Application")
Set wdDoc = wdApp.ActiveDocument
Set wdDocPro = wdDoc.BuiltInDocumentProperties.Item(1) ' I get a type mismatch on this line
For Each wdDocPro In wdDoc.BuiltInDocumentProperties
MsgBox (wdDocPro.Name & " , " & wdDocPro.Value)
Next wdDocPro
End Sub
此测试使我能够看到“wdDoc”的文档属性,因此我知道这一定是 1.) DocumentProperty 的 Excel 与 Word 对象模型或 2.) 该函数以某种方式失去对 Word 的访问的问题.Document内置文档属性集合
当我到达将 wdDocPro 设置为内置文档属性项的行时,Excel VBA 中的这段代码出现问题。
Public Sub GetCurrentFolderConstants()
Dim DocVariables() As String
Dim wdApp as Word.Application
Dim wdDoc as Word.Document
Set wdApp = GetObject(, "Word.Application")
Set wdDoc = wdApp.ActiveDocument
DocVariables = DocVarGrabbing(wdDoc)
'Do stuff
wdDoc.Close True
'Do stuff with DocVariables
wdApp.Quit SaveChanges:=False
End Sub
'''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''
Public Function DocVarGrabbing(ByRef wdDoc As Word.Document) As String()
Dim wdDocPro As DocumentProperty 'Problem variable
'Set wdApp = GetObject(, "Word.Application")
'Set wdDoc = wdApp.ActiveDocument
'MsgBox wdDoc.Name
If wdDoc.BuiltinDocumentProperties.Count > 0 Then
Set wdDocPro = wdDoc.BuiltinDocumentProperties.Item(1)'I get a type mismatch at this line
For Each wdDocPro In ActiveDocument.BuiltinDocumentProperties
'Do stuff with Document properties Names and Values and assign to DocVarArray (not needed for debugging)
Next wdDocPro
End If
DocVarGrabbing = DocVarArray
Set wdDocPro = Nothing
End Function
最佳答案
本主题中的 DocumentProperty
类型原则上应为 Office.DocumentProperty
类型 - 并且 DocumentProperties
将是 Office.DocumentProperties
对象实例(VSTO documentation 似乎同意),并且对象浏览器仅在 Office
类型中找到具有该名称的单个类库 - 所以这不是关于 Excel 与 Word 的问题:既不定义任何 DocumentProperties
或 DocumentProperty
类。
这是一个问题。接下来的事情是,当您在进程外(例如,从 Excel 工作簿的 VBA 项目中检查 Word 文档,或检查 Excel Word 文档的 VBA 项目中的工作簿属性):
Public Function GetWordDocProps(ByVal doc As Word.Document) As Variant
Dim properties As Variant 'Office.DocumentProperties
Set properties = doc.BuiltinDocumentProperties
Dim prop As Variant 'Office.DocumentProperty
Set prop = properties.Item(1)
If Not TypeOf properties Is Office.DocumentProperties Then Debug.Print TypeName(properties) 'prints "DocumentProperties"
If Not TypeOf prop Is Office.DocumentProperty Then Debug.Print TypeName(prop) 'prints "DocumentProperty"
'...
End Function
当您忽略类型并将所有内容视为Variant
时,所有内容都“正常工作”..但后期绑定(bind),因此请注意拼写错误,如果您尝试调用以下成员,则会出现错误 438:不存在。
关于excel - 如何将 Excel DocumentProperty 对象变量(位于 ByRef 函数中)设置为 WordbuiltinDocumentProperties 集合项?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54045815/