I'm trying to read some customXMLnodes from a customXMLpart using VBA to populate some content controls in Microsoft word. For my code sample below I'm just printing the immediate window as I attempt to debug this issue.

I can do this without problems when I read a customXMLnode that is inside of a customXMLpart that has no namespace. However, when trying to read a node in a customXMLpart that has a namespace, I get run-time error 91 (object variable not set) at the line where it attempts to output to the immediate window (see my comments in the code sample below). I've set a breakpoint before this to try to figure this out and it shows that the node (cxn in my code below) is set to Nothing. I'm not sure what I'm doing wrong.

The XML is:

<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<People xmlns="people">
    <Person>
        <Name> bob </Name>
        <Street> Main St. </Street>
    </Person>
</People>`

The VBA is:

Dim cxp1 As CustomXMLParts
Dim cxn As CustomXMLNode

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

' Get the node matching the XPath expression.
Set cxn = cxp1(1).SelectSingleNode("/People/Person/Name")
'executing the line below gives me run-time error 91 (object variable not 
'set). And cxn shows that it is set to Nothing.  
Debug.Print cxn.Text

I essentially got this code from a Microsoft website https://docs.microsoft.com/en-us/office/vba/api/office.customxmlparts.selectbynamespace and made some slight changes for my specific XML.

I believe I have the proper Dim and Set statements so it is unclear why I'm getting this error. I know the XML is good because I can read it when there is no namespace when using VBA as follows:

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

Any advice is very appreciated!

0 Answers