How to Parse XML Using VBA: A Step-by-Step Guide

Parsing XML can seem daunting at first, especially for those who are new to the world of VBA. If you find yourself needing to access values from an XML structure, such as extracting X and Y coordinates from a point, you’ve come to the right place! In this post, we will explore the process of parsing XML in VBA to extract data efficiently.

The Problem: Extraction of X and Y Values

Imagine you have an XML string that looks like this:

<PointN xsi:type='typens:PointN' 
xmlns:xsi='http://www.w3.org/2001/XMLSchema-instance' 
xmlns:xs='http://www.w3.org/2001/XMLSchema'>
    <X>24.365</X>
    <Y>78.63</Y>
</PointN>

You want to extract the values of X and Y so that you can store them as integer variables within your VBA code. As a newbie in XML and VBA, the question arises: How do I achieve this?

The Solution: Using MSXML2.DOMDocument

Fortunately, there is a straightforward method to parse XML data using the MSXML2.DOMDocument object in VBA. Here are the steps you should follow:

Step 1: Set Up MSXML2 Reference

Before you begin coding, ensure you have referenced the Microsoft XML, v6.0 library in your VBA editor. Here’s how:

  1. Open your VBA editor (Press ALT + F11).
  2. Click on Tools > References.
  3. Look for Microsoft XML, v6.0 and check the box next to it.
  4. Click OK.

Step 2: Load the XML String

You can load your XML string into a DOMDocument as follows:

Dim xmlDoc As Object
Set xmlDoc = CreateObject("MSXML2.DOMDocument.6.0")

xmlDoc.LoadXML "<PointN xsi:type='typens:PointN' xmlns:xsi='http://www.w3.org/2001/XMLSchema-instance' xmlns:xs='http://www.w3.org/2001/XMLSchema'><X>24.365</X><Y>78.63</Y></PointN>"

Step 3: Access the X and Y Nodes

Once the XML structure is loaded, you can easily access the X and Y values using the selectSingleNode method:

Dim xValue As Double
Dim yValue As Double

xValue = xmlDoc.SelectSingleNode("//X").Text
yValue = xmlDoc.SelectSingleNode("//Y").Text

Step 4: Store as Integer Variables

If needed, you can convert these values to integers:

Dim xInt As Integer
Dim yInt As Integer

xInt = CInt(xValue)
yInt = CInt(yValue)

Summary of Steps

  1. Set up the reference to MSXML2.
  2. Load your XML string into a DOMDocument.
  3. Use selectSingleNode to get the values of X and Y.
  4. Convert the values to integers if necessary.

Conclusion

Parsing XML in VBA might seem complicated at first, but with the MSXML2.DOMDocument object, it becomes a much simpler task. By following these steps, you can easily extract values from XML structures and utilize them in your work.

For further reading and exploration, consider visiting the following resources:

With this guide, you’ll be well-equipped to tackle XML parsing in your VBA projects. Happy coding!