XML files are one of the most common type of data files apart from text and CSV (comma-separated values) files. Reading data files which are not hierarchical (as XML files or JSON) is relatively easy. You can read in the data row by row and process columns separately. With XML (and JSON) the task is not as easy as the data is hierarchical (parent-child relationships exist between records in the schema) and the number of underlying nodes may vary as opposed to tabular data which usually has a constant number of columns separated with a specific delimiter.
Fortunately, we can use the MSXML2.DOMDocument object in VBA. Let’s however, as always, start with a short introduction as to how XML files a structure before we dive into the examples.
Loading XML document in VBA
The MSXML2.DOMDocument object allows you to easily traverse through an XML structure an extract any XML node and/or attribute needed. Let’s look at the example below.
Below we start by loading the XML document. Notice that I am selecting the load to be performed synchronously and not validation be carried out on parsing the document. Feel free to change these options if needed.
Sub TestXML() Dim XDoc As Object, root as Object Set XDoc = CreateObject("MSXML2.DOMDocument") XDoc.async = False: XDoc.validateOnParse = False XDoc.Load (ThisWorkbook.Path & "test.xml") Set root = XDoc.DocumentElement '... End Sub
Alternatively load an XML from a string:
Sub TestXML() Dim XDoc As Object, root as Object Set XDoc = CreateObject("MSXML2.DOMDocument") XDoc.async = False: XDoc.validateOnParse = False XDoc.LoadXML ("<root><child></child></root>") Set root = XDoc.DocumentElement '... End Sub
That’s it. You have loaded the XML document into memory into the DOMDocument object. The document has been parsed and you can easily traverse the enclosed elements. See next section.
XML DOM nodes in VBA
For the below I will use the following examples XML:
<?xml version="1.0" encoding="utf-8"?> <DistributionLists> <List> <Name>Recon</Name> <TO>John;Bob;Rob;Chris</TO> <CC>Jane;Ashley</CC> <BCC>Brent</BCC> </List> <List> <Name>Safety Metrics</Name> <TO>Tom;Casper</TO> <CC>Ashley</CC> <BCC>John</BCC> </List> <List> <Name>Performance Report</Name> <TO>Huck;Ashley</TO> <CC>Tom;Andrew</CC> <BCC>John;Seema</BCC> </List> </DistributionLists>
The XML document will provide you with the root of the entire DOM (of type XDoc.DocumentElement). Each DocumentElement (XML DOM node) facilitates the following node references:
Node Reference | Type | Description |
---|---|---|
parentNode | [XDoc.DocumentElement] | The parent node, one node higher in the DOM hierarchy |
firstChild | [XDoc.DocumentElement] | The first child node, first node lower in the DOM hierarchy |
lastChild | [XDoc.DocumentElement] | The last child node, last node lower in the DOM hierarchy |
childNodes | [Array of type XDoc.DocumentElement] | All child nodes of the current node, all nodes lower in the DOM hierarchy |
nextSibling | [XDoc.DocumentElement] | Next sibling node i.e. node on the same level in the DOM hierarchy, having the same parent node |
previousSibling | [XDoc.DocumentElement] | Previous sibling node i.e. node on the same level in the DOM hierarchy, having the same parent node |
All the above references allow you to free move within the XML DOM.
ChildNodes
Let’s start by extracting the first list and printing it’s XML and text contents. The basics to moving around the XML DOM is using ChildNodes.
Sub TestXML() Dim XDoc As Object Set XDoc = CreateObject("MSXML2.DOMDocument") XDoc.async = False: XDoc.validateOnParse = False XDoc.Load (ThisWorkbook.Path & "test.xml") 'Get Document Elements Set lists = XDoc.DocumentElement 'Get first child ( same as ChildNodes(0) ) Set getFirstChild = lists.FirstChild 'Print first child XML Debug.Print getFirstChild.XML 'Print first child Text Debug.Print getFirstChild.Text Set XDoc = Nothing End Sub
This is the result
'Print first child XML <List> <Name>Recon</Name> <TO>John;Bob;Rob;Chris</TO> <CC>Jane;Ashley</CC> <BCC>Brent</BCC> </List> 'Print first child Text Recon John;Bob;Rob;Chris Jane;Ashley Brent
Traversing through the whole XML in VBA
Now that we got the basics let’s print out the whole contents of the XML DOM including the basenames (node names).
Sub TestXML() Dim XDoc As Object Set XDoc = CreateObject("MSXML2.DOMDocument") XDoc.async = False: XDoc.validateOnParse = False XDoc.Load (ThisWorkbook.Path & "test.xml") 'Get Document Elements Set lists = XDoc.DocumentElement 'Traverse all elements 2 branches deep For Each listNode In lists.ChildNodes Debug.Print "---Email---" For Each fieldNode In listNode.ChildNodes Debug.Print "[" & fieldNode.BaseName & "] = [" & fieldNode.Text & "]" Next fieldNode Next listNode Set XDoc = Nothing End Sub
This is the result:
---Email--- [Name] = [Recon] [TO] = [John;Bob;Rob;Chris] [CC] = [Jane;Ashley] [BCC] = [Brent] ---Email--- [Name] = [Safety Metrics] [TO] = [Tom;Casper] [CC] = [Ashley] [BCC] = [John] ---Email--- [Name] = [Performance Report] [TO] = [Huck;Ashley] [CC] = [Tom;Andrew] [BCC] = [John;Seema]
Easy right? Using the basics above we can easily move around the document. But this still seems like a lot of coding right? Well there is an easier way of moving / extracting items using the DOMDocument object – called XPath.
XML Document example node references
Now that we have a hang of our XML document, based on the example XML I provided above I mapped a reference to how to obtain various elements of our XML file by using node references:
- DistributionLists [FirstChild]
- List [ChildNodes(0)]
- Name: Recon [ChildNodes(0).ChildNodes(0).innerText]
- TO: John;Bob;Rob;Chris [ChildNodes(0).ChildNodes(1).innerText]
- CC: Jane;Ashley
- BCC: Brent
- List [ChildNodes(1)]
- Name: Performance Report [ChildNodes(1).ChildNodes(0).innerText]
- TO: Huck;Ashley
- CC: Tom;Andrew
- BCC: John;Seema
(…)
- List [ChildNodes(0)]
XPath in VBA
Instead of traversing the elements/nodes in your XML using the .ChildNodes/.FirstChild/NextChild properties we can also use XPath. XPath is a query language used for selecting XML nodes in an XML document. It is represented by a single string. It allows you to extract any number of nodes (0 or more) which match the specified XPath query.
If you want to learn XPath I can recommend this overview:
https://www.w3schools.com/xml/xpath_syntax.asp
Now let’s jump into an example:
Example 1: Extract all Lists
Sub TestXML() Dim XDoc As Object Set XDoc = CreateObject("MSXML2.DOMDocument") XDoc.async = False: XDoc.validateOnParse = False XDoc.Load (ThisWorkbook.Path & "test.xml") Set lists = XDoc.SelectNodes("//DistributionLists/List") Set XDoc = Nothing End Sub
Example 2: Extracting all TO fields
Set toFields = XDoc.SelectNodes("//DistributionLists/List/TO") End Sub
Example 3: Extracting the first and last Name field
Set firstNameField = XDoc.SelectNodes("//DistributionLists/List[0]/Name") Set lastNameField = XDoc.SelectNodes("//DistributionLists/List[2]/Name")
Example 3: Extracting all child List nodes (Name, TO, CC, BCC)
Set listChildrenField = XDoc.SelectNodes("//DistributionLists/List/*")
XML Attributes in VBA
Let’s tackle one last example – attributes. Let’s slightly modify the XML above and include an example attribute named attribute.
<?xml version="1.0" encoding="utf-8"?> <DistributionLists> <List> <Name attribute="some">Recon</Name>
Using XPath (or traversing the DOM) we can easily extract the attribute as shown below.
Set firstNameField = XDoc.SelectNodes("//DistributionLists/List[0]/Name") Debug.Print firstNameField(0).Attributes(0).Text 'Result: "some"
Creating XML documents
Creating documents is also quite straight forward in VBA.
Dim XDoc As Object, root As Object, elem As Object Set XDoc = CreateObject("MSXML2.DOMDocument") Set root = XDoc.createElement("Root") XDoc.appendChild root 'Add child to root Set elem = XDoc.createElement("Child") root.appendChild elem 'Add Attribute to the child Dim rel As Object Set rel = XDoc.createAttribute("Attrib") rel.NodeValue = "Attrib value" elem.setAttributeNode rel 'Save the XML file XDoc.Save "C:my_file.xml"
Excel VBA XML
The full form of XML is eXtensible Markup Language which is much like an HTML file, is designed to store and transport the data from different programs. XML file stores the data which includes the splits and separators. We can create a VBA code by which we can import the data from the XML file into Excel. In order to import the data from the XML file to any other format, we need to set some rules which tells what kind of data and fields can be used in the XML file. To create a macro in VBA for the XML file, we do not mandatory need XML Notepad in our system. But if we have it will be easy for us to read the XML file for the data we need.
Although in Excel, we have a provision of importing the data of XML file but using VBA, we can read, import the XML file in Excel.
Types of Node in VBA XML
In XML, we have a variety of Nodes that constructively helps in reading and parsing the XML file into other sources such as Word or Excel. Each DocumentElement refers to some of the nodes lists below.
- Parent Node
- First Child
- Last Child
- Child Nodes
- Next Sibling
- Previous Sibling
All the above-mentioned nodes confirm the type as [XDoc.DocumentElement], where only Child nodes are the array type of [XDoc.DocumentElement].
In this example, we will see a very simple VBA Code to access the XML file saved in the individual system’s any location and load them into VBA. Usually, to import XML files in Excel using VBA, we have MSXML2.DOMDocument object to allow us to transverse the data through XML structure. But this may not be used in this example.
For this, we must have an XML file in which we can create a data structure in the form of Schema. Below is the screenshot of Company schema where under that we have Employee branch with the employee details like First Name, Last Name, Contact Number, Email ID.
Steps to Import & Add XML in Excel VBA
Below are the examples of XML in Excel by using the VBA Code.
You can download this VBA XML Excel Template here – VBA XML Excel Template
Example #1
Step 1: First go to Insert menu tab in VBA and open a Module where we will be writing the code transverse data through XML as shown below.
Step 2: Write the subprocedure in the name of VBA XML for the definition of the code.
Code:
Sub VBA_XML() End Sub
Step 3: As we already discussed, for the XML file we will require Object. So, Now define a variable using DIM as String which will be used for storing the File name.
Code:
Sub VBA_XML() Dim XMLFile As String End Sub
Step 4: Now we will use an application Display Alerts which is used for showing the alert message if the chosen path is incorrect.
Code:
Sub VBA_XML() Dim XMLFile As String Application.DisplayAlerts = False End Sub
Step 5: Now we will put the link or location where we have kept XML file and assign it to the defined variable.
Code:
Sub VBA_XML() Dim XMLFile As String Application.DisplayAlerts = False XMLFile = "C:AshwaniCompany.xml" End Sub
Note: Keep the XML file in the location which is easy to access.
Step 6: As we discussed, we will get the first Object with MSXML2.DOMDoucment.
Code:
Sub VBA_XML() Dim CusDoc As Object Dim Base As Object Set CusDoc = CreateObject("MSXML2.DOMDoucment") End Sub
Step 7: To load the data of XML file in Excel, we need to open that XML file, using the name and location which we have stored in XML File variable and select the load option as Import to List as shown below.
Code:
Sub VBA_XML() Dim XMLFile As String Application.DisplayAlerts = False XMLFile = "C:AshwaniCompany.xml" Workbooks.OpenXML Filename:=XMLFile, LoadOption:=xlXmlLoadImportToList End Sub
Step 8: At last, again use the Application option to display the alert as TRUE if there is any.
Code:
Sub VBA_XML() Dim XMLFile As String Application.DisplayAlerts = False XMLFile = "C:AshwaniCompany.xml" Workbooks.OpenXML Filename:=XMLFile, LoadOption:=xlXmlLoadImportToList Application.DisplayAlerts = True End Sub
Step 9: Now we will compile the written code by pressing F8 functional key and run it, if there is no error found during compilation.
We will see, the data stored in the XML file is not imported in a new workbook as shown below. We can fetch any length of data of XML file into Excel using this simple VBA Code.
Example #2
There is another way to import the data of an XML file using the VBA Code which is simple too. For this, we can have another module of we can make the changes in the same module as well.
Step 1: For this again we would require a module and there write the subprocedure in the name of VBA XML.
Code:
Sub VBA_XML2() End Sub
Step 2: Define a variable as String where we will be storing the file location and another variable for Workbook as shown below.
Code:
Sub VBA_XML2() Dim XMLFile As String Dim WBook As Workbook End Sub
Step 3: Now similar to the previous example we will now use 2 Applications, one of Screen updating and other for Display Alerts as FALSE.
Code:
Sub VBA_XML2() Dim XMLFile As String Dim WBook As Workbook Application.ScreenUpdating = False Application.DisplayAlerts = False End Sub
Step 4: Now in the defined variable XMLFile, we will assign the path of the XML file.
Code:
Sub VBA_XML2() Dim XMLFile As String Dim WBook As Workbook Application.ScreenUpdating = False Application.DisplayAlerts = False XMLFile = "C:AshwaniCompany.xml" End Sub
Step 5: Similar to example-1, we will now update set the code for Opening XML file with the path defined in XMLFile variable and load the data Import to list.
Code:
Sub VBA_XML2() Dim XMLFile As String Dim WBook As Workbook Application.ScreenUpdating = False Application.DisplayAlerts = False XMLFile = "C:AshwaniCompany.xml" Set WBook = Workbooks.OpenXML(Filename:=XMLFile, LoadOption:=xlXmlLoadImportToList) End Sub
Step 6: Now again to put the Display alert application as TRUE.
Code:
Sub VBA_XML2() Dim XMLFile As String Dim WBook As Workbook Application.ScreenUpdating = False Application.DisplayAlerts = False XMLFile = "C:AshwaniCompany.xml" Set WBook = Workbooks.OpenXML(Filename:=XMLFile, LoadOption:=xlXmlLoadImportToList) Application.DisplayAlerts = True End Sub
Step 7: Once the data is imported we will copy that into another workbook from the selected cell A1:D1 as per the number of headers available in the XML file.
Code:
Sub VBA_XML2() Dim XMLFile As String Dim WBook As Workbook Application.ScreenUpdating = False Application.DisplayAlerts = False XMLFile = "C:AshwaniCompany.xml" Set WBook = Workbooks.OpenXML(Filename:=XMLFile, LoadOption:=xlXmlLoadImportToList) Application.DisplayAlerts = True WBook.Sheets(1).UsedRange.Copy ThisWorkbook.Sheets(1).Range("A1:D1") End Sub
Step 8: At last close the code using Screen updating application as TRUE.
Code:
Sub VBA_XML2() Dim XMLFile As String Dim WBook As Workbook Application.ScreenUpdating = False Application.DisplayAlerts = False XMLFile = "C:AshwaniCompany.xml" Set WBook = Workbooks.OpenXML(Filename:=XMLFile, LoadOption:=xlXmlLoadImportToList) Application.DisplayAlerts = True WBook.Sheets(1).UsedRange.Copy ThisWorkbook.Sheets(1).Range("A1:D1") Application.ScreenUpdating = True End Sub
Step 9: Now if we run this code, we will see the data from the XML file will get imported into a new Excel workbook as shown below.
Pros of VBA XML
- Even if you do not know how to create an XML file and work on it, using such VBA codes, we can extract the data into VBA Code or in Excel.
- We can parse a portion of XML Data or complete data into the VBA window by using node references.
Things to Remember
- Every node reference has its own value and meaning. Using the right note type is very important for every condition.
- XML to VBA is not limited to the code which we have seen in the above examples.
- We can extract any type of data using the code which we have seen in above-discussed examples. But keep the proper location and path which is easy to access.
- We can also extract the XML file data without opening it from the developer tab’s Source option. This will help us to get the data as it is into the Excel workbook.
- Save the written code Excel file in Macro enabled excel format, to avoid losing the code.
Recommended Articles
This is a guide to the VBA XML. Here we discuss Steps to Import & Add XML in Excel VBA and its different types of node along with practical examples and downloadable excel template. You can also go through our other suggested articles –
- VBA LBound
- VBA Get Cell Value
- VBA IsError
- VBA Solver
So, I’ve got a bunch of content that was delivered to us in the form of Excel spreadsheets. I need to take that content and push it into another system. The other system takes its input from an XML file. I could do all of this by hand (and trust me, management has no problem making me do that!), but I’m hoping there’s an easy way to write an Excel macro that would generate the XML I need instead. This seems like a better solution to me, as this is a job that will need to be repeated regularly (we’ll be getting a LOT of content in Excel sheets) and it just makes sense to have a batch tool that does it for us.
However, I’ve never experimented with generating XML from Excel spreadsheets before. I have a little VBA knowledge but I’m a newbie to XML. I guess my problem in Googling this is that I don’t even know what to Google for. Can anyone give me a little direction to get me started? Does my idea sound like the right way to approach this problem, or am I overlooking something obvious?
Thanks StackOverflow!
asked May 4, 2010 at 15:40
You might like to consider ADO — a worksheet or range can be used as a table.
Const adOpenStatic = 3
Const adLockOptimistic = 3
Const adPersistXML = 1
Set cn = CreateObject("ADODB.Connection")
Set rs = CreateObject("ADODB.Recordset")
''It wuld probably be better to use the proper name, but this is
''convenient for notes
strFile = Workbooks(1).FullName
''Note HDR=Yes, so you can use the names in the first row of the set
''to refer to columns, note also that you will need a different connection
''string for >=2007
strCon = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" & strFile _
& ";Extended Properties=""Excel 8.0;HDR=Yes;IMEX=1"";"
cn.Open strCon
rs.Open "Select * from [Sheet1$]", cn, adOpenStatic, adLockOptimistic
If Not rs.EOF Then
rs.MoveFirst
rs.Save "C:DocsTable1.xml", adPersistXML
End If
rs.Close
cn.Close
answered May 4, 2010 at 17:02
FionnualaFionnuala
90.1k7 gold badges110 silver badges148 bronze badges
2
Credit to: curiousmind.jlion.com/exceltotextfile (Link no longer exists)
Script:
Sub MakeXML(iCaptionRow As Integer, iDataStartRow As Integer, sOutputFileName As String)
Dim Q As String
Q = Chr$(34)
Dim sXML As String
sXML = "<?xml version=" & Q & "1.0" & Q & " encoding=" & Q & "UTF-8" & Q & "?>"
sXML = sXML & "<rows>"
''--determine count of columns
Dim iColCount As Integer
iColCount = 1
While Trim$(Cells(iCaptionRow, iColCount)) > ""
iColCount = iColCount + 1
Wend
Dim iRow As Integer
iRow = iDataStartRow
While Cells(iRow, 1) > ""
sXML = sXML & "<row id=" & Q & iRow & Q & ">"
For icol = 1 To iColCount - 1
sXML = sXML & "<" & Trim$(Cells(iCaptionRow, icol)) & ">"
sXML = sXML & Trim$(Cells(iRow, icol))
sXML = sXML & "</" & Trim$(Cells(iCaptionRow, icol)) & ">"
Next
sXML = sXML & "</row>"
iRow = iRow + 1
Wend
sXML = sXML & "</rows>"
Dim nDestFile As Integer, sText As String
''Close any open text files
Close
''Get the number of the next free text file
nDestFile = FreeFile
''Write the entire file to sText
Open sOutputFileName For Output As #nDestFile
Print #nDestFile, sXML
Close
End Sub
Sub test()
MakeXML 1, 2, "C:Usersjlyndsoutput2.xml"
End Sub
indofraiser
9943 gold badges17 silver badges50 bronze badges
answered Mar 13, 2014 at 10:30
SolataSolata
1,3943 gold badges29 silver badges42 bronze badges
3
Here is the example macro to convert the Excel worksheet to XML file.
#'vba code to convert excel to xml
Sub vba_code_to_convert_excel_to_xml()
Set wb = Workbooks.Open("C:temptestwb.xlsx")
wb.SaveAs fileName:="C:temptestX.xml", FileFormat:= _
xlXMLSpreadsheet, ReadOnlyRecommended:=False, CreateBackup:=False
End Sub
This macro will open an existing Excel workbook from the C drive and Convert the file into XML and Save the file with .xml extension in the specified Folder. We are using Workbook Open method to open a file. SaveAs method to Save the file into destination folder. This example will be help full, if you wan to convert all excel files in a directory into XML (xlXMLSpreadsheet format) file.
answered Sep 3, 2020 at 8:31
This one more version — this will help in generic
Public strSubTag As String
Public iStartCol As Integer
Public iEndCol As Integer
Public strSubTag2 As String
Public iStartCol2 As Integer
Public iEndCol2 As Integer
Sub Create()
Dim strFilePath As String
Dim strFileName As String
'ThisWorkbook.Sheets("Sheet1").Range("C3").Activate
'strTag = ActiveCell.Offset(0, 1).Value
strFilePath = ThisWorkbook.Sheets("Sheet1").Range("B4").Value
strFileName = ThisWorkbook.Sheets("Sheet1").Range("B5").Value
strSubTag = ThisWorkbook.Sheets("Sheet1").Range("F3").Value
iStartCol = ThisWorkbook.Sheets("Sheet1").Range("F4").Value
iEndCol = ThisWorkbook.Sheets("Sheet1").Range("F5").Value
strSubTag2 = ThisWorkbook.Sheets("Sheet1").Range("G3").Value
iStartCol2 = ThisWorkbook.Sheets("Sheet1").Range("G4").Value
iEndCol2 = ThisWorkbook.Sheets("Sheet1").Range("G5").Value
Dim iCaptionRow As Integer
iCaptionRow = ThisWorkbook.Sheets("Sheet1").Range("B3").Value
'strFileName = ThisWorkbook.Sheets("Sheet1").Range("B4").Value
MakeXML iCaptionRow, iCaptionRow + 1, strFilePath, strFileName
End Sub
Sub MakeXML(iCaptionRow As Integer, iDataStartRow As Integer, sOutputFilePath As String, sOutputFileName As String)
Dim Q As String
Dim sOutputFileNamewithPath As String
Q = Chr$(34)
Dim sXML As String
'sXML = sXML & "<rows>"
' ''--determine count of columns
Dim iColCount As Integer
iColCount = 1
While Trim$(Cells(iCaptionRow, iColCount)) > ""
iColCount = iColCount + 1
Wend
Dim iRow As Integer
Dim iCount As Integer
iRow = iDataStartRow
iCount = 1
While Cells(iRow, 1) > ""
'sXML = sXML & "<row id=" & Q & iRow & Q & ">"
sXML = "<?xml version=" & Q & "1.0" & Q & " encoding=" & Q & "UTF-8" & Q & "?>"
For iCOl = 1 To iColCount - 1
If (iStartCol = iCOl) Then
sXML = sXML & "<" & strSubTag & ">"
End If
If (iEndCol = iCOl) Then
sXML = sXML & "</" & strSubTag & ">"
End If
If (iStartCol2 = iCOl) Then
sXML = sXML & "<" & strSubTag2 & ">"
End If
If (iEndCol2 = iCOl) Then
sXML = sXML & "</" & strSubTag2 & ">"
End If
sXML = sXML & "<" & Trim$(Cells(iCaptionRow, iCOl)) & ">"
sXML = sXML & Trim$(Cells(iRow, iCOl))
sXML = sXML & "</" & Trim$(Cells(iCaptionRow, iCOl)) & ">"
Next
'sXML = sXML & "</row>"
Dim nDestFile As Integer, sText As String
''Close any open text files
Close
''Get the number of the next free text file
nDestFile = FreeFile
sOutputFileNamewithPath = sOutputFilePath & sOutputFileName & iCount & ".XML"
''Write the entire file to sText
Open sOutputFileNamewithPath For Output As #nDestFile
Print #nDestFile, sXML
iRow = iRow + 1
sXML = ""
iCount = iCount + 1
Wend
'sXML = sXML & "</rows>"
Close
End Sub
answered May 6, 2016 at 7:10
2
It is pretty easy to exchange data between Excel & VBA and XML file. XML files are one of the most common files other than Txt and CSV. It is easier to read non-hierarchical data files (XML or JSON). You can read the rows and columns differently in the code line. It is not that easy to check data with XML (and JSON.) There are parent-child relations between the records in the templates and the number of underlying nodes can be changed corresponding to the table data that contain a stable number on columns. This has been separated with a certain delimiter.
Fortunately, we can easily exchange data between Excel & VBA and XML file by using the MSXML2.DOMDocument object in VBA.
But, as always, let’s start with a short introduction concerning how to create a while before we deep into the examples of a structure in XML.
Microsoft Excel, makes it easy to import Extensible Markup Language (XML) data created on out databases and applications, pair XML objects coming from XML schema with the workbook cells and export XML data to interact with out databases and applications. You can think of it as these XML features turns Office Excel in to a XML data file creater that works with a familiar user interface.
Now let’s take a look at this VBA & XML.
Upload XML File to VBA
The MSXML2.DomDocument object enables you to access XML structure easily and provides movement between any required node and/or quality with the XML structure. Let’s take a look at the example below.
Sub PEAKUP() Dim Xml As Object, root As Object Set Xml = CreateObject("MSXML2.DOMDocument") Xml.async = False: Xml.validateOnParse = False Xml.Load (ThisWorkbook.Path & "etf.xml") Set root = Xml.DocumentElement End Sub
XML DOM Nodes in VBA
XML file will provide you with the root of all the DOM(XDoc.DocumentElement Model).
Each DocumentElement (XML DOM node) facilitated the node references below:
parentNode | Parent node, the top node in the DOM hierarchy |
firstChild | First child node, the first child node in the DOM hierarchy |
lastChild | Last child node, the last child node in the DOM hierarchy |
childNodes | All child nodes of the node, all nodes in the DOM hierarchy |
nextSibling | The same-level node in the same master node in the DOM hierarchy, i.e. the next sibling node. |
previousSibling | The same-level node in the same master node in the DOM hierarchy, i.e. the previous sibling node. |
All the references below help you to access the data in XML DOM.
childNodes
Let’s take the first node as an example and have the text content as MsgBox. We usually use ChildNodes while exploring nodes in XML DOM.
Sub PEAKUP() Dim XDoc As Object Set XDoc = CreateObject("MSXML2.DOMDocument") XDoc.async = False: XDoc.validateOnParse = False XDoc.Load (ThisWorkbook.Path & "etf.xml") Set lists = XDoc.DocumentElement Set ilkdugum = lists.FirstChild MsgBox ilkdugum.Xml MsgBox ilkdugum.Text Set XDoc = Nothing End Sub
You can download this file and test the codes below.
Now that we’ve got all the basic information, we can write the all content of XML to Excel with these codes.
Sub PEAKUP() Dim XDoc As Object Set XDoc = CreateObject("MSXML2.DOMDocument") XDoc.async = False: XDoc.validateOnParse = False XDoc.Load (ThisWorkbook.Path & "etf.xml") Set lists = XDoc.DocumentElement For Each satirNode In lists.ChildNodes For Each alandNode In rowNode.ChildNodes a = a + 1 Cells(a, 1) = "[" & alanNode.BaseName & "] = [" & alanNode.Text & "]" Next alanNode Next satirNode Set XDoc = Nothing End Sub
You’ll see that you can do this action with the examples below as well.
XML Attributes in VBA
You can get the attribute values states as current attribute in the XML Nodes. Let’s assume that you have an XML structure like this:
<?xml version="1.0" encoding="utf-8"?> <AnaDugum> <Liste> <Adi attribute="PEAKUP">ORG</Adi>
You can get the attributes easily with XPath as shown below.
Set adialani = XDoc.SelectNodes("//AnaDugum/Liste[0]/Adi") MsgBox adialani(0).Attributes(0).Text
Create an XML File
ub XML_Belge_Olusturma() Dim XDoc As Object, root As Object, elem As Object, rel As Object Set XDoc = CreateObject("MSXML2.DOMDocument") Set root = XDoc.createElement("Root") XDoc.appendChild root Set elem = XDoc.createElement("Child") root.appendChild elem Set rel = XDoc.createAttribute("Oznitelik") rel.NodeValue = "PEAKUP" elem.setAttributeNode rel XDoc.Save ThisWorkbook.Path & "yeni.xml" End Sub
In addition to the information above, I want to share a few code blocks that can be used to Import Data from an XML file, Search and Delete.
To list all the data in the XML file:
Sub XML_Dosyasını_Okuma() Dim Etf As Object, ayır() As String, i As Integer Set Etf = CreateObject("MSXML2.DOMDocument") Etf.async = False If Etf.Load(ThisWorkbook.Path & "etf.xml") Then ayır = Split(Etf.Text, " ") For i = 0 To UBound(ayır) Cells(i + 1, 1) = ayır(i) Next i End If Set Etf = Nothing: Erase ayır: i = Empty End Sub
To list all the data in the management Node in the XML file:
DefObj I, N, R Sub XML_Dosyasından_Veri_Alma() Dim i As Integer Set Etf = CreateObject("MSXML2.DOMDocument") Etf.async = False Etf.Load (ThisWorkbook.Path & "etf.xml") Set Nod = Etf.SelectNodes("//yonetim/*") For Each Item In Nod i = i + 1 Cells(i, 1) = Item.Text Next Item Set Etf = Nothing: Set Nod = Nothing Set Item = Nothing: i = Empty End Sub
To list the information of the person named Murat in the management Node in XML file:
DefObj I, N, R Sub XML_Dosyasından_Veri_Alma() Dim i As Integer Set Etf = CreateObject("MSXML2.DOMDocument") Etf.async = False Etf.Load (ThisWorkbook.Path & "etf.xml") Set Nod = Etf.SelectNodes("//yonetim[ad='Murat']") For Each Item In Nod i = i + 1 Cells(i, 1) = Item.Text Next Item Set Etf = Nothing: Set Nod = Nothing Set Item = Nothing: i = Empty End Sub
To list the information of people whose City name is Istanbul in management node in XML file:
DefObj I, N, R Sub XML_Dosyasından_Veri_Alma() Dim i As Integer Set Etf = CreateObject("MSXML2.DOMDocument") Etf.async = False Etf.Load (ThisWorkbook.Path & "etf.xml") Set Nod = Etf.SelectNodes("//yonetim[sehir='Istanbul']") For Each Item In Nod i = i + 1 Cells(i, 1) = Item.Text Next Item Set Etf = Nothing: Set Nod = Nothing Set Item = Nothing: i = Empty End Sub
To list the information of the person named Emre with the SelectsingleNode method in management node in XML file:
DefObj I, N, R Sub XML_Dosyasından_Veri_Alma() Dim i As Integer Set Etf = CreateObject("MSXML2.DOMDocument") Etf.async = False Etf.Load (ThisWorkbook.Path & "etf.xml") Set Nod = Etf.SelectSingleNode("//yonetim[ad='Emre']") Range("A1").Value = Nod.Text Set Etf = Nothing: Set Nod = Nothing Set Item = Nothing: i = Empty End Sub
To remove “Murat OSMA” in the site_management group from the list and save as new.xml in the management node in XML file:(you can write on the old file too).
DefObj I, N, R Sub Nod_Silme() Set Etf = CreateObject("MSXML2.DOMDocument") Etf.async = False Etf.Load (ThisWorkbook.Path & "etf.xml") Set Nod = Etf.SelectNodes("//yonetim[ad='Murat']") For Each Item In Nod Item.ParentNode.RemoveChild Item Next Item Etf.Save ThisWorkbook.Path & "yeni.xml" End Sub
You can check Microsoft Docs for more details.
See you in other articles, bye. 🙋🏻♂️
You can share this post with your friends and get them informed as well.👍🏻
Reading XML into Excel
One interesting use for Excel is using it as a platform for calling web services.
While the Web Browser is the obvious platform for sending and receiving web based data,
sometimes Excel is a better application to analyse formatted lists or numerical data.
Excel gives you the ability to import and query data via web services.
Excel VBA — Loading XML string defined in program into VBA XML DOM Document
In this example we define an XML string, load the string and use it to populate a DOM document.
Sub XMLTest01() 'In Tools > References, add reference to "Microsoft XML, vX.X" before running. 'create instance of the DOMDocument object: Dim xmlDoc As MSXML2.DOMDocument Set xmlDoc = New MSXML2.DOMDocument Dim strXML As String 'create XML string strXML = "<fullName>" & _ "<firstName>Bob</firstName>" & _ "<lastName>Smith</lastName>" & _ "</XXXfullName>" ' use XML string to create a DOM, on error show error message If Not xmlDoc.LoadXML(strXML) Then Err.Raise xmlDoc.parseError.ErrorCode, , xmlDoc.parseError.reason End If End Sub
XML error message: Note that there is an error in the terminating the XML fullname tag
Some VBA vocabulary
MSXML2.DOMDocument
The DOMDocument object represents the top node in the tree. It implements all of the base Document Object Model (DOM) document methods and provides additional members that support Extensible Stylesheet Language (XSL) and XML transformations. Only one object can be created: the document. All other objects are accessed or created from the document.
LoadXML
Loads an XML document using the supplied string.
Loading XML in Excel VBA — Enhanced error reporting
Sub XMLTest02() 'In Tools > References, add reference to "Microsoft XML, vX.X" before running. 'create instance of the DOMDocument class: Dim xmlDoc As MSXML2.DOMDocument Set xmlDoc = New MSXML2.DOMDocument Dim strErrText As String Dim xmlError As MSXML2.IXMLDOMParseError Dim strXML As String 'create XML string strXML = "<fullName>" & _ "<firstName>Bob</firstName>" & _ "<lastName>Smith</lastName>" & _ "</XXXfullName>" ' use XML string to create a DOM, on error show error message If Not xmlDoc.LoadXML(strXML) Then ' get the ParseError object Set xmlError = xmlDoc.parseError With xmlError strErrText = "Your XML Document failed to load" & _ "due the following error." & vbCrLf & _ "Error #: " & .ErrorCode & ": " & xmlError.reason & _ "Line #: " & .Line & vbCrLf & _ "Line Position: " & .linepos & vbCrLf & _ "Position In File: " & .filepos & vbCrLf & _ "Source Text: " & .srcText & vbCrLf End With ' Display error & exit program MsgBox strErrText, vbExclamation Set xmlDoc = Nothing End End If End Sub
XML error message: Note that there is an error in the terminating the XML fullname tag
Reading an XML file into Excel
'In Tools > References, add reference to "Microsoft XML, vX.X" before running. Sub subReadXMLStream() Dim xmlDoc As MSXML2.DOMDocument Dim xEmpDetails As MSXML2.IXMLDOMNode Dim xParent As MSXML2.IXMLDOMNode Dim xChild As MSXML2.IXMLDOMNode Dim Col, Row As Integer Set xmlDoc = New MSXML2.DOMDocument xmlDoc.async = False xmlDoc.validateOnParse = False ' use XML string to create a DOM, on error show error message If Not xmlDoc.Load("http://itpscan.info/blog/excel/xml/schedule.xml") Then Err.Raise xmlDoc.parseError.ErrorCode, , xmlDoc.parseError.reason End If Set xEmpDetails = xmlDoc.DocumentElement Set xParent = xEmpDetails.FirstChild Row = 1 Col = 1 Dim xmlNodeList As IXMLDOMNodeList Set xmlNodeList = xmlDoc.SelectNodes("//record") For Each xParent In xmlNodeList For Each xChild In xParent.ChildNodes Worksheets("Sheet1").Cells(Row, Col).Value = xChild.Text Debug.Print Row & " - "; Col & " - " & xChild.Text Col = Col + 1 Next xChild Row = Row + 1 Col = 1 Next xParent End Sub
Some VBA vocabulary
MSXML2.IXMLDOMNode
The IXMLDOMNode object provides methods that represent the core functionality of any node.
async
XML DOM property that specifies whether asynchronous download is permitted.
validateOnParse
XML DOM property that indicates whether the parser should validate this document.
FirstChild
Gets the first child of the node.
output in MS Excel:
Clear cache
This code is useful if you are using Apache Basic Athorization and user changes their userid/password.
Even if the code creates a brand new XMLHttpReq object and sets this header to the new information,
it logs in to the server as the first user, presumably from cached credentials. This code eventively clears the cache
in most browsers and lets user log in with a new username/password combination.
Sub subClearCache() ' force browser to clear cache myURL = "http://172.16.50.250/blackberry/BBTESTB01.pgm" Dim oHttp As New MSXML2.XMLHTTP oHttp.Open "POST", myURL, False oHttp.setRequestHeader "Content-Type", "application/x-www-form-urlencoded" oHttp.setRequestHeader "Cache-Control", "no-cache" oHttp.setRequestHeader "PragmaoHttp", "no-cache" oHttp.setRequestHeader "If-Modified-Since", "Sat, 1 Jan 2000 00:00:00 GMT" oHttp.setRequestHeader "Authorization", "Basic " & Base64EncodedUsernamePassword oHttp.send "PostArg1=PostArg1Value" Result = oHttp.responseText End Sub
- Importance of an XML Parser
- Build XML Parser Using VBA
- Conclusion
This article will teach us how to parse XML files in VBA.
Importance of an XML Parser
As a Microsoft Excel user, it is common that you might receive some data in the form of an XML file. You will have to retrieve the information from the XML file and use it in your sheets or VBA macros according to your requirement.
A way to do this is to treat it as a text file and parse the information. But this is not an elegant way to parse XML files since the information is stored well-structured using tags, and treating it as a text file negates this concept.
Therefore, we will have to make use of an XML Parser. An XML Parser reads the XML file and retrieves the relevant data so it can be used readily.
Build XML Parser Using VBA
We can parse an XML file using VBA and convert the data into our Excel sheet. The method we will be using uses the XML DOM
implementation, short for the XML Document Object Model, and this model allows us to represent the XML file as an object we can then manipulate as required.
To start parsing your XML file through VBA, you must perform a simple sequence of steps. These are explained below.
To parse XML through VBA, you need to have MSXML.4.0
or greater on your system.
-
Add Reference to Microsoft XML
First, you need to add a reference to
Microsoft XML, V6.0
in the VBA Editor. This is how it is done:Open the VBA Editor from the Developer tab in Excel.
-
Scroll down and check
Microsoft XML, V6.0
, then click onOK
.Note that the version of Microsoft XML depends on the operating system and Microsoft Office installed on your computer.
-
Write VBA Code to Load the XML File Into
XML DOM
Suppose we have the following XML file:
<?xml version="1.0" encoding="ISO8859-1" ?> <menu> <food> <name> Halwa Puri </name> <price> $7.50 </price> <description> Halwa Puri is from Indian and Pakistani cuisines, having the sweet Halwa and the savory Puri which is a fried flatbread. </description> <calories> 900 </calories> </food> </menu>
We can use the following code to parse this XML file through VBA by making an
XML DOM
object in the following way:Sub XMLParser() Dim xDoc As New MSXML2.DOMDocument60 Dim node As IXMLDOMElement Set xDoc = New MSXML2.DOMDocument60 With xDoc .async = False .validateOnParse = True If xDoc.Load("D:VBAexample.xml") = False Then Debug.Print .parseError.reason, .parseError.ErrorCode Exit Sub End If Set node = xDoc.SelectSingleNode("//price") MsgBox node.Text End With End Sub
In the code above, we have first created a variable xDoc
of the MSXML2.DOMDocument60
type. Here, we have appended 60
at the end because we are using version 6.0
of Microsoft XML
, and without the 60
, this code will generate a compile-time error of User-defined type not found
.
Next, we have specified that we are working with the xDoc
variable using the With
statement. The .async
property defines permission for asynchronous downloads, and the .validateOnParse
property indicates if the parser should validate the XML
document.
After that, we use the .Load
function to load the specified XML
file into the DOM
variable. Here, you can change the path and file name to the one on your computer.
The next two lines are for error handling in case the XML
file is not loaded properly. To test if the loading has worked, we take one node from the file and specify its name as price
.
You should note that the node name is case-sensitive and must be specified according to your XML
file. Finally, we display the price using the node.Text
property in a message box.
Output:
This shows that the loading has worked perfectly fine.
One way to use the XML file data is to store it in an Excel sheet. Let us make a few changes to the code above to store the data in the Excel sheet:
Sub XMLParser()
Dim xDoc As New MSXML2.DOMDocument60
Set xDoc = New MSXML2.DOMDocument60
Dim list As MSXML2.IXMLDOMNodeList
Dim osh As Worksheet
Set osh = ThisWorkbook.Sheets("Sheet1")
oRow = 1
With xDoc
.async = False
.validateOnParse = True
If xDoc.Load("D:VBAexample.xml") = False Then
Debug.Print .parseError.reason, .parseError.ErrorCode
Exit Sub
End If
Set list = xDoc.SelectNodes("//price")
loopCount = 0
For Each node In list
oRow = oRow + 1
osh.Range("A" & oRow) = node.Text
Next
End With
End Sub
Here, we are retrieving all the price
nodes and storing them in the sheet. In this example, we have only one price
node that will be saved into the sheet as follows:
You can tweak the code according to your XML file and requirements.
Conclusion
This sums up our discussion on the method to parse XML
files through VBA. In this article, we have learned how to build an XML parser using XML DOM
in VBA.
Read XML using Excel VBA
XML is the file format that is widely used to transfer data over internet or between 2 systems with different platforms. The most widely used & familiar xml file in the internet world is the Sitemap.xml. This file has the major links to a website.
Other widely used file formats for data transfer are JSON, CSV. In this article, we are going to learn how to read the xml file using XML DOM (Data Object Model).
Excel VBA XML Parser
Using this tutorial you can build a XML parser using Excel VBA. Lets start with this step by step procedure. Open an Excel Workbook & Open VB Editor by pressing Alt + F11. Then follow these important steps.
- Add reference to “Microsoft XML, V6.0” from Excel VB editor.
- VB Editor -> Menu->Tools -> Reference
- Scroll down till Microsoft XML, V2.0 or 3.0 or 6.0 appears. The version of XML depends on the OS & Office version installed in your machine.
- Click Ok.
- Now, Copy paste the code to your VBE.
- Download a file from Internet or if you have a file already, Modify the xml file path in the code.
- Run the code by pressing F5.
'-------------------------------------------------------------------------------- 'Code by author@officetricks.com 'Visit https://officetricks.com to get more Free & Fully Functional VBA Codes '-------------------------------------------------------------------------------- Public Sub Xml_To_Excel() Dim myURL As String, sFileNamePath As String, dsh As Worksheet, osh As Worksheet Dim WinHttpReq As Object, Node As IXMLDOMNode Dim xDoc As MSXML2.DOMDocument Dim list As MSXML2.IXMLDOMNodeList 'Create XML DOM Object Set xDoc = New MSXML2.DOMDocument Set osh = ThisWorkbook.Sheets("Sheet2") oRow = 1 'This is only a sample xml file - Change the File path to your Xml file path fname = "http://www.xmlfiles.com/examples/simple.xml" 'Load Xml file to Object & Process Each node. If xDoc.Load(fname) Then Set list = xDoc.SelectNodes("//breakfast-menu/food") loopCount = 0 Application.Wait DateAdd("s", 5, Now) DoEvents For Each Node In list oRow = oRow + 1 '***Note: node names are Casesensitive*** osh.Range("A" & oRow) = Node.SelectSingleNode("name").Text osh.Range("B" & oRow) = Node.Text Next Else MsgBox "Error Occured" End If MsgBox "Process Completed" End Sub
This code uses XML DOM model to parse each node from input xml file. Then write it to the Excel file one by one.
Содержание
- Метод Workbook.XmlImport (Excel)
- Синтаксис
- Параметры
- Возвращаемое значение
- Замечания
- Поддержка и обратная связь
- Метод Workbook.SaveAsXMLData (Excel)
- Синтаксис
- Параметры
- Замечания
- Пример
- Поддержка и обратная связь
- How to parse XML using vba
- 8 Answers 8
- Parsing XML in Microsoft Excel VBA
- Importance of an XML Parser
- Build XML Parser Using VBA
- Conclusion
- VBA XML
- Excel VBA XML
- Types of Node in VBA XML
- Steps to Import & Add XML in Excel VBA
- Example #1
- Example #2
- Pros of VBA XML
- Things to Remember
- Recommended Articles
Метод Workbook.XmlImport (Excel)
Импортирует XML-файл данных в текущую книгу.
Синтаксис
expression. XmlImport (URL-адрес, ImportMap, перезапись, назначение)
Выражение Переменная, представляющая объект Workbook .
Параметры
Имя | Обязательный или необязательный | Тип данных | Описание |
---|---|---|---|
Url | Обязательный | String | Универсальный указатель ресурсов (URL-адрес) или UNC-путь к XML-файлу данных. |
ImportMap | Обязательный | XmlMap | Схема, применяемая при импорте файла. Если данные были импортированы ранее, содержит ссылку на объект XmlMap , содержащий данные. |
Overwrite | Необязательный | Variant | Если значение не указано для параметра Destination , этот параметр указывает, следует ли перезаписывать данные, сопоставленные с картой схемы, указанной в параметре ImportMap . Задайте значение True , чтобы перезаписать данные, или False , чтобы добавить новые данные к существующим данным. Значение по умолчанию — True. |
Если для параметра Destination задано значение, этот параметр указывает, следует ли перезаписывать существующие данные. Установите значение True , чтобы перезаписать существующие данные, или Значение False , чтобы отменить импорт, если данные будут перезаписаны. Значение по умолчанию — True. Destination Необязательный Variant Указывает диапазон, в котором будет создан список. Используйте только левый верхний угол диапазона.
Возвращаемое значение
Замечания
Этот метод позволяет импортировать данные в книгу из пути к файлу. Excel использует первую найденную сопоставимую карту или, если указан диапазон назначения, Excel автоматически выводит данные.
Не указывайте значение для параметра Destination , если вы хотите импортировать данные в существующее сопоставление.
Следующие условия приводят к возникновению ошибок во время выполнения методом XmlImport :
Указанные XML-данные содержат синтаксические ошибки.
Процесс импорта был отменен, так как указанные данные не могут поместиться на лист.
Если соответствующие карты не найдены и диапазон назначения не указан.
Используйте метод XmlImportXml объекта Workbook для импорта XML-данных, которые ранее были загружены в память.
Поддержка и обратная связь
Есть вопросы или отзывы, касающиеся Office VBA или этой статьи? Руководство по другим способам получения поддержки и отправки отзывов см. в статье Поддержка Office VBA и обратная связь.
Источник
Метод Workbook.SaveAsXMLData (Excel)
Экспортирует данные, сопоставленные с указанной схемой XML, в XML-файл данных.
Синтаксис
expression. SaveAsXMLData (FileName, Map)
Выражение Переменная, представляющая объект Workbook .
Параметры
Имя | Обязательный или необязательный | Тип данных | Описание |
---|---|---|---|
FileName | Обязательный | String | Строка, указывающая имя сохраняемого файла. Можно включить полный путь; В противном случае Microsoft Excel сохранит файл в текущей папке. |
Map | Обязательный | XmlMap | Схема, применяемая к данным. |
Замечания
Этот метод приводит к ошибке во время выполнения, если Excel не удается экспортировать данные с указанной схемой. Чтобы проверить, может ли Excel использовать указанную схему для экспорта данных, используйте свойство IsExportable .
Пример
В следующем примере проверяется, что Excel может использовать схему Customer для экспорта данных, а затем экспортирует данные, сопоставленные с картой схемы клиента, в файл с именем Customer Data.xml.
Поддержка и обратная связь
Есть вопросы или отзывы, касающиеся Office VBA или этой статьи? Руководство по другим способам получения поддержки и отправки отзывов см. в статье Поддержка Office VBA и обратная связь.
Источник
How to parse XML using vba
I work in VBA, and want to parse a string eg
and get the X & Y values into two separate integer variables.
I’m a newbie when it comes to XML, since I’m stuck in VB6 and VBA, because of the field I work in.
How do I do this?
8 Answers 8
Thanks for the pointers.
I don’t know, whether this is the best approach to the problem or not, but here is how I got it to work. I referenced the Microsoft XML, v2.6 dll in my VBA, and then the following code snippet, gives me the required values
This is a bit of a complicated question, but it seems like the most direct route would be to load the XML document or XML string via MSXML2.DOMDocument which will then allow you to access the XML nodes.
You can find more on MSXML2.DOMDocument at the following sites:
Add reference Project->References Microsoft XML, 6.0 and you can use example code:
be careful with xml node //Root/Person is not same with //root/person, also selectSingleNode(«Name»).text is not same with selectSingleNode(«name»).text
You can use a XPath Query:
This is an example OPML parser working with FeedDemon opml files:
This one takes multilevel trees of folders (Awasu, NewzCrawler):
but I don’t understand, why xmldoc4 should be loaded each time.
Update
The procedure presented below gives an example of parsing XML with VBA using the XML DOM objects. Code is based on a beginners guide of the XML DOM.
Nota Bene — This initial answer shows the simplest possible thing I could imagine (at the time I was working on a very specific issue) . Naturally using the XML facilities built into the VBA XML Dom would be much better. See the updates above.
Original Response
I know this is a very old post but I wanted to share my simple solution to this complicated question. Primarily I’ve used basic string functions to access the xml data.
This assumes you have some xml data (in the temp variable) that has been returned within a VBA function. Interestingly enough one can also see how I am linking to an xml web service to retrieve the value. The function shown in the image also takes a lookup value because this Excel VBA function can be accessed from within a cell using = FunctionName(value1, value2) to return values via the web service into a spreadsheet.
Источник
Parsing XML in Microsoft Excel VBA
This article will teach us how to parse XML files in VBA.
Importance of an XML Parser
As a Microsoft Excel user, it is common that you might receive some data in the form of an XML file. You will have to retrieve the information from the XML file and use it in your sheets or VBA macros according to your requirement.
A way to do this is to treat it as a text file and parse the information. But this is not an elegant way to parse XML files since the information is stored well-structured using tags, and treating it as a text file negates this concept.
Therefore, we will have to make use of an XML Parser. An XML Parser reads the XML file and retrieves the relevant data so it can be used readily.
Build XML Parser Using VBA
We can parse an XML file using VBA and convert the data into our Excel sheet. The method we will be using uses the XML DOM implementation, short for the XML Document Object Model, and this model allows us to represent the XML file as an object we can then manipulate as required.
To start parsing your XML file through VBA, you must perform a simple sequence of steps. These are explained below.
To parse XML through VBA, you need to have MSXML.4.0 or greater on your system.
Add Reference to Microsoft XML
First, you need to add a reference to Microsoft XML, V6.0 in the VBA Editor. This is how it is done:
Open the VBA Editor from the Developer tab in Excel.
In the menu, go to Tools > References.
Scroll down and check Microsoft XML, V6.0 , then click on OK .
Note that the version of Microsoft XML depends on the operating system and Microsoft Office installed on your computer.
Write VBA Code to Load the XML File Into XML DOM
Suppose we have the following XML file:
We can use the following code to parse this XML file through VBA by making an XML DOM object in the following way:
In the code above, we have first created a variable xDoc of the MSXML2.DOMDocument60 type. Here, we have appended 60 at the end because we are using version 6.0 of Microsoft XML , and without the 60 , this code will generate a compile-time error of User-defined type not found .
Next, we have specified that we are working with the xDoc variable using the With statement. The .async property defines permission for asynchronous downloads, and the .validateOnParse property indicates if the parser should validate the XML document.
After that, we use the .Load function to load the specified XML file into the DOM variable. Here, you can change the path and file name to the one on your computer.
The next two lines are for error handling in case the XML file is not loaded properly. To test if the loading has worked, we take one node from the file and specify its name as price .
You should note that the node name is case-sensitive and must be specified according to your XML file. Finally, we display the price using the node.Text property in a message box.
This shows that the loading has worked perfectly fine.
One way to use the XML file data is to store it in an Excel sheet. Let us make a few changes to the code above to store the data in the Excel sheet:
Here, we are retrieving all the price nodes and storing them in the sheet. In this example, we have only one price node that will be saved into the sheet as follows:
You can tweak the code according to your XML file and requirements.
Conclusion
This sums up our discussion on the method to parse XML files through VBA. In this article, we have learned how to build an XML parser using XML DOM in VBA.
Hello, I am Bilal, a research enthusiast who tends to break and make code from scratch. I dwell deep into the latest issues faced by the developer community and provide answers and different solutions. Apart from that, I am just another normal developer with a laptop, a mug of coffee, some biscuits and a thick spectacle!
Источник
VBA XML
Excel VBA XML
The full form of XML is eXtensible Markup Language which is much like an HTML file, is designed to store and transport the data from different programs. XML file stores the data which includes the splits and separators. We can create a VBA code by which we can import the data from the XML file into Excel. In order to import the data from the XML file to any other format, we need to set some rules which tells what kind of data and fields can be used in the XML file. To create a macro in VBA for the XML file, we do not mandatory need XML Notepad in our system. But if we have it will be easy for us to read the XML file for the data we need.
Although in Excel, we have a provision of importing the data of XML file but using VBA, we can read, import the XML file in Excel.
Valuation, Hadoop, Excel, Mobile Apps, Web Development & many more.
Types of Node in VBA XML
In XML, we have a variety of Nodes that constructively helps in reading and parsing the XML file into other sources such as Word or Excel. Each DocumentElement refers to some of the nodes lists below.
- Parent Node
- First Child
- Last Child
- Child Nodes
- Next Sibling
- Previous Sibling
All the above-mentioned nodes confirm the type as [XDoc.DocumentElement], where only Child nodes are the array type of [XDoc.DocumentElement].
In this example, we will see a very simple VBA Code to access the XML file saved in the individual system’s any location and load them into VBA. Usually, to import XML files in Excel using VBA, we have MSXML2.DOMDocument object to allow us to transverse the data through XML structure. But this may not be used in this example.
For this, we must have an XML file in which we can create a data structure in the form of Schema. Below is the screenshot of Company schema where under that we have Employee branch with the employee details like First Name, Last Name, Contact Number, Email ID.
Steps to Import & Add XML in Excel VBA
Below are the examples of XML in Excel by using the VBA Code.
Example #1
Step 1: First go to Insert menu tab in VBA and open a Module where we will be writing the code transverse data through XML as shown below.
Step 2: Write the subprocedure in the name of VBA XML for the definition of the code.
Code:
Step 3: As we already discussed, for the XML file we will require Object. So, Now define a variable using DIM as String which will be used for storing the File name.
Code:
Step 4: Now we will use an application Display Alerts which is used for showing the alert message if the chosen path is incorrect.
Code:
Step 5: Now we will put the link or location where we have kept XML file and assign it to the defined variable.
Code:
Step 6: As we discussed, we will get the first Object with MSXML2.DOMDoucment.
Code:
Step 7: To load the data of XML file in Excel, we need to open that XML file, using the name and location which we have stored in XML File variable and select the load option as Import to List as shown below.
Code:
Step 8: At last, again use the Application option to display the alert as TRUE if there is any.
Code:
Step 9: Now we will compile the written code by pressing F8 functional key and run it, if there is no error found during compilation.
We will see, the data stored in the XML file is not imported in a new workbook as shown below. We can fetch any length of data of XML file into Excel using this simple VBA Code.
Example #2
There is another way to import the data of an XML file using the VBA Code which is simple too. For this, we can have another module of we can make the changes in the same module as well.
Step 1: For this again we would require a module and there write the subprocedure in the name of VBA XML.
Code:
Step 2: Define a variable as String where we will be storing the file location and another variable for Workbook as shown below.
Code:
Step 3: Now similar to the previous example we will now use 2 Applications, one of Screen updating and other for Display Alerts as FALSE.
Code:
Step 4: Now in the defined variable XMLFile, we will assign the path of the XML file.
Code:
Step 5: Similar to example-1, we will now update set the code for Opening XML file with the path defined in XMLFile variable and load the data Import to list.
Code:
Step 6: Now again to put the Display alert application as TRUE.
Code:
Step 7: Once the data is imported we will copy that into another workbook from the selected cell A1:D1 as per the number of headers available in the XML file.
Code:
Step 8: At last close the code using Screen updating application as TRUE.
Code:
Step 9: Now if we run this code, we will see the data from the XML file will get imported into a new Excel workbook as shown below.
Pros of VBA XML
- Even if you do not know how to create an XML file and work on it, using such VBA codes, we can extract the data into VBA Code or in Excel.
- We can parse a portion of XML Data or complete data into the VBA window by using node references.
Things to Remember
- Every node reference has its own value and meaning. Using the right note type is very important for every condition.
- XML to VBA is not limited to the code which we have seen in the above examples.
- We can extract any type of data using the code which we have seen in above-discussed examples. But keep the proper location and path which is easy to access.
- We can also extract the XML file data without opening it from the developer tab’s Source option. This will help us to get the data as it is into the Excel workbook.
- Save the written code Excel file in Macro enabled excel format, to avoid losing the code.
Recommended Articles
This is a guide to the VBA XML. Here we discuss Steps to Import & Add XML in Excel VBA and its different types of node along with practical examples and downloadable excel template. You can also go through our other suggested articles –
Источник
-
December 26 2011, 09:26
Полезная вводная статья о том, как загружать XML в Excel-VBA:
A Beginner’s Guide to the XML DOM
P.S. А это — еще одна статья на форуме, в дополнение к первой:
VBA. Импорт XML в Excel
Результатом стала простая тестовая программа в духе Hello world:
Sub Main() Dim xmlDoc As MSXML2.DOMDocument Dim xmlNodes As IXMLDOMNodeList Dim xmlNode As IXMLDOMNode Set xmlDoc = New MSXML2.DOMDocument Dim source source = ThisWorkbook.Path & "test.xml" resp = xmlDoc.Load(source) If Not resp Then cdd = xmlDoc.parseError.ErrorCode rsn = xmlDoc.parseError.reason lnn = xmlDoc.parseError.Line pss = xmlDoc.parseError.linepos src = xmlDoc.parseError.srcText MsgBox cdd & " | " & rsn & " | " & lnn & " | " & pss & " | " & src Else Set xmlNodes = xmlDoc.SelectNodes("//child") For Each xmlNode In xmlNodes MsgBox xmlNode.Text Next End If End Sub
Файл «test.xml»:
<?xml version="1.0" encoding="utf-8"?> <root> <child>Hello, world!</child> </root>
Данная программа реализована на VBA. Чтобы она заработала, не забудьте подключить библиотеку MSXML2. Для этого в редакторе MS VBA выберите Tools > References и найдите в списке Microsoft XML, v.5.0. Отметьте строку галочкой, нажмите ОК.