Home » excel » How to read a XML self-closing tag in Excel VBA?

How to read a XML self-closing tag in Excel VBA?

Posted by: admin April 23, 2020 Leave a comment


I have a XML file that contains a tag that can either have text or can be self-closing when it has no text.

Case 1 (with text):


Case 2 (no text – self-closing):

   <size />

I want to read this tag text in Excel VBA.
In Case 1, no problem, I do the following:

Set oXMLFile = CreateObject("Microsoft.XMLDOM")
oXMLFile.Load ("File.xml")
size = oXMLFile.SelectSingleNode("/Example/size/text()").NodeValue

But in Case 2, the SelectSingleNode function returns this error:

Run-time error ‘438’:
Object doesn’t support this property or method

How can I handle Case 2 so that it returns me an empty string? Is there a built-in VBA function to test if a tag is self-closing?

How to&Answers:
Option Explicit

Sub Test()

    Dim oXMLFile As Object
    Dim oNode As Object
    Dim sSize As String

    Set oXMLFile = CreateObject("MSXML2.DOMDocument.6.0")
    oXMLFile.LoadXML "<Example><size>512</size></Example>"
    Set oNode = oXMLFile.SelectSingleNode("/Example/size/text()")
    If Not oNode Is Nothing Then sSize = oNode.NodeValue

End Sub