Vba 运行时错误91:CustomXMLnode上未设置对象变量

Vba 运行时错误91:CustomXMLnode上未设置对象变量,vba,ms-word,Vba,Ms Word,我正在尝试使用VBA从customXMLpart读取一些customXMLnodes,以填充Microsoft word中的一些内容控件。对于下面的代码示例,我只是在尝试调试此问题时打印即时窗口 我可以在读取customXMLpart中没有命名空间的customXMLnode时执行此操作。但是,当尝试读取customXMLpart中具有名称空间的节点时,我得到 运行时错误91(未设置对象变量) 在它试图输出到即时窗口的行(请参见下面代码示例中的注释) 在此之前我设置了一个断点,它显示节点(下面代

我正在尝试使用VBA从customXMLpart读取一些customXMLnodes,以填充Microsoft word中的一些内容控件。对于下面的代码示例,我只是在尝试调试此问题时打印即时窗口

我可以在读取customXMLpart中没有命名空间的customXMLnode时执行此操作。但是,当尝试读取customXMLpart中具有名称空间的节点时,我得到

运行时错误91(未设置对象变量)

在它试图输出到即时窗口的行(请参见下面代码示例中的注释)

在此之前我设置了一个断点,它显示节点(下面代码中的cxn)设置为Nothing

XML是:

<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<People xmlns="people">
    <Person>
        <Name> bob </Name>
        <Street> Main St. </Street>
    </Person>
</People>`
我从微软网站上获得了这段代码,并对我的特定XML做了一些细微的更改

我知道XML很好,因为我可以在使用VBA时在没有命名空间的情况下读取它,如下所示:

Dim parts As CustomXMLParts
Dim part As CustomXMLPart

Dim nodes As CustomXMLNodes
Dim node As CustomXMLNode

Set parts = ActiveDocument.CustomXMLParts

For Each part In parts

    If Len(part.NamespaceURI) = 0 Then
        Set node = part.SelectSingleNode("/People/Person/Name")
        debug.Print = node.Text
Dim cxp1 As CustomXMLParts
Dim cxn As CustomXMLNode
Dim prefix As String

' Returns all of the custom xml parts with the given namespace.
Set cxp1 = ActiveDocument.CustomXMLParts.SelectByNamespace("people")
prefix = cxp1(1).NamespaceManager.LookupPrefix("people")

' Get the node matching the XPath expression using the prefix variable (even 
'if you don't explicitly set a prefix you must include a prefix)
Set cxn = cxp1(1).SelectSingleNode("/" & prefix & ":" & People & "/" & prefix & 
":" & Person & "/" & prefix & ":" & Name")
Debug.Print cxn.Text
编辑:此错误已解决

要读取具有命名空间的customXML部件,节点上的Xpath必须包含XML前缀。这很让人困惑,因为我没有前缀,但显然MS Word指定了一个前缀。因此,必须将CustomXMLpart的前缀作为字符串变量获取,并使用该变量更改Xpath表达式,如下所示:

Dim parts As CustomXMLParts
Dim part As CustomXMLPart

Dim nodes As CustomXMLNodes
Dim node As CustomXMLNode

Set parts = ActiveDocument.CustomXMLParts

For Each part In parts

    If Len(part.NamespaceURI) = 0 Then
        Set node = part.SelectSingleNode("/People/Person/Name")
        debug.Print = node.Text
Dim cxp1 As CustomXMLParts
Dim cxn As CustomXMLNode
Dim prefix As String

' Returns all of the custom xml parts with the given namespace.
Set cxp1 = ActiveDocument.CustomXMLParts.SelectByNamespace("people")
prefix = cxp1(1).NamespaceManager.LookupPrefix("people")

' Get the node matching the XPath expression using the prefix variable (even 
'if you don't explicitly set a prefix you must include a prefix)
Set cxn = cxp1(1).SelectSingleNode("/" & prefix & ":" & People & "/" & prefix & 
":" & Person & "/" & prefix & ":" & Name")
Debug.Print cxn.Text

这看起来是关于如何处理自定义xml的一个很好的来源:感谢您的帮助。我没有从那个网站上得到答案,但我非常感谢您提供的资源。这看起来是一个关于如何处理自定义xml的很好的来源:谢谢您的帮助。我没有从那个网站得到答案,但我非常感谢你提供的资源。