Xml from excel vba

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

SuperNES's user avatar

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

Fionnuala's user avatar

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's user avatar

indofraiser

9943 gold badges17 silver badges50 bronze badges

answered Mar 13, 2014 at 10:30

Solata's user avatar

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

Tamil Selvan S's user avatar

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

Vinoth Krishnan's user avatar

answered May 6, 2016 at 7:10

Bhaghawadgeetha Sundaram's user avatar

2

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.

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.

VBA XML Code

VBA XML Tree

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.

Insert Module

Step 2: Write the subprocedure in the name of VBA XML for the definition of the code.

Code:

Sub VBA_XML()

End Sub

VBA XML Example 1-2

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

VBA XML Example 1-3

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

VBA XML Example 1-4

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

VBA XML Example 1-5

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

VBA XML Example 1-6

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

VBA XML Example 1-7

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

VBA XML Example 1-8

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.

VBA XML Example 1-8

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

VBA XML Example 2-1

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

VBA XML Example 2-2

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

VBA XML Example 2-3

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

Defined Variable Example 2-4

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

VBA XML Example 2-5

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

Display Alert Application Example 2-6

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

Workbook Example 2-7

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

Screen updating application Example 2-8

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.

VBA XML Example 2-9

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 –

  1. VBA LBound
  2. VBA Get Cell Value
  3. VBA IsError
  4. VBA Solver

Содержание

  1. Метод Workbook.XmlImport (Excel)
  2. Синтаксис
  3. Параметры
  4. Возвращаемое значение
  5. Замечания
  6. Поддержка и обратная связь
  7. Метод Workbook.SaveAsXMLData (Excel)
  8. Синтаксис
  9. Параметры
  10. Замечания
  11. Пример
  12. Поддержка и обратная связь
  13. How to parse XML using vba
  14. 8 Answers 8
  15. Parsing XML in Microsoft Excel VBA
  16. Importance of an XML Parser
  17. Build XML Parser Using VBA
  18. Conclusion
  19. VBA XML
  20. Excel VBA XML
  21. Types of Node in VBA XML
  22. Steps to Import & Add XML in Excel VBA
  23. Example #1
  24. Example #2
  25. Pros of VBA XML
  26. Things to Remember
  27. 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 –

Источник

Краткая справка:

Microsoft Excel — Программа для работы с электронными таблицами. Она предоставляет возможности экономико-статистических расчетов, графические инструменты и язык макропрограммирования VBA (Visual Basic for Application).

Visual Basic for Applications (VBA, Visual Basic для приложений) — немного упрощённая реализация языка программирования Visual Basic, встроенная в линейку продуктов Microsoft Office, а также во многие другие программные пакеты.

XML(англ. eXtensible Markup Language — расширяемый язык разметки). XML — язык с простым формальным синтаксисом, удобный для создания и обработки документов программами и одновременно удобный для чтения и создания документов человеком. Разработчик волен создать разметку в соответствии с потребностями к конкретной области, будучи ограниченным лишь синтаксическими правилами языка.

Задача:

Экспортировать данные из таблицы Excel и сформировать XML-файл с заданной структурой для последующей обработки сторонними программными продуктами.

Исходная таблица с некоторыми данными:

Код VBA:

Sub exportXML()

    'Путь для сохранения итогового XML
    xmlFile = ActiveWorkbook.Path & "export.xml"
    
    'Строка и столбец расположения названия компании
    Dim company_row As Integer
    company_row = 1
    Dim company_col As Integer
    company_col = 1
    
    'Номер строки начала таблицы с данными
    Dim data_row As Integer
    data_row = 3
    
    'Номер столбца "Порядковый номер"
    Dim num_col As Integer
    num_col = 1
    
    'Номер столбца "ФИО"
    Dim name_col As Integer
    name_col = 2
    
    'Номер столбца "Профессия"
    Dim profession_col As Integer
    profession_col = 3
    
    'Номер столбца "Наличность"
    Dim profit_col As Integer
    profit_col = 4


    'Cоздание объекта XML
    Set xml = CreateObject("MSXML2.DOMDocument")
    'Добавление описания XML
    xml.appendChild xml.createProcessingInstruction("xml", "version='1.0' encoding='utf-8'")
    
    'Добавление корневого элемента "company"
    Set Company = xml.createElement("company")
    'Добавление атрибута "name"
    Company.setAttribute "name", Cells(company_row, company_col)
    xml.appendChild (Company)
    
    'Цикл по строкам (пока не встретится строка с пустым "Порядковым номером")
    Do While Not IsEmpty(Cells(data_row, num_col))
       'Вызов функции добавления сотрудника компании
        Company.appendChild (createPerson(xml, Cells(data_row, num_col), _
                               Cells(data_row, name_col), _
                               Cells(data_row, profession_col), _
                               Cells(data_row, profit_col)))
        'Переход к следующей строке таблицы
        data_row = data_row + 1
    Loop
        
    'Выполнение XSL-преобразования для добавления отступов в XML
    Call transformXML(xml)
    
    'Сохранение файла (без выбора пути сохранения, удобно при отладке)
    'xml.Save xmlFile
    'MsgBox "Export complete!"

    'Сохранение файла (с выбором пути сохранения)
    xml.Save Application.GetSaveAsFilename("", "Файл экспорта (*.xml),", , "Введите имя файла", "Сохранить")

End Sub


'Функция добавления сотрудника компании(xml, "Порядковый номер", "ФИО", "Профессия", "Наличность") возвращает узел XML
Function createPerson(ByRef xml As Variant, ByVal num As Variant, ByVal name As Variant, _
                      ByVal profession As Variant, ByVal profit As Variant) As Variant

    'Создание элемента person
    Set createPerson = xml.createElement("person")
    createPerson.setAttribute "num", num
    
    'Добавление в виде комментария "Профессия" (просто для примера)
    createPerson.appendChild (xml.createComment(profession))

    'Создание элементов для столбцов "ФИО" и "Наличность"
    createPerson.appendChild(xml.createElement("name")).Text = name
    createPerson.appendChild(xml.createElement("profit")).Text = profit
    
End Function


'Процедура для придания XML читабельного вида (с отступами)
Sub transformXML(ByRef xml As Variant)

    'Cоздание объекта XSL
    Set xsl = CreateObject("MSXML2.DOMDocument")
    
    'Загрузка XSL из строки (не требует наличия отдельного XSL-файла)
    xsl.LoadXML ("<xsl:stylesheet version='1.0' xmlns:xsl='http://www.w3.org/1999/XSL/Transform'>" & vbCrLf & _
    "<xsl:output method='xml' version='1.0' encoding='UTF-8' indent='yes'/>" & vbCrLf & _
    "<xsl:template match='@*|node()'>" & vbCrLf & _
    "<xsl:copy>" & vbCrLf & _
    "<xsl:apply-templates select='@*|node()' />" & vbCrLf & _
    "</xsl:copy>" & vbCrLf & _
    "</xsl:template>" & vbCrLf & _
    "</xsl:stylesheet>")
    
    'Выполнение преобразования
    xml.transformNodeToObject xsl, xml

End Sub

Результат в виде XML:

<?xml version="1.0" encoding="UTF-8"?>

<company name="ООО 'Рога и копыта'">
	<person num="1">
		<!--Великий комбинатор-->
		<name>Остап Ибрагимович Бендер</name>
		<profit>225000</profit>
	</person>
	<person num="2">
		<!--Нарушитель конвенции-->
		<name>Михаил Самуэлевич Паниковский</name>
		<profit>30000</profit>
	</person>
	<person num="3">
		<!--Водитель автомобиля «Антилопа-Гну»-->
		<name>Адам Казимирович Козлевич</name>
		<profit>95000</profit>
	</person>
	<person num="4">
		<!--Подпольный миллионер-->
		<name>Александр Иванович Корейко</name>
		<profit>1000000</profit>
	</person>
	<person num="5">
		<!--Сын лейтенанта Шмидта-->
		<name>Шура Балаганов</name>
		<profit>50000</profit>
	</person>
</company>

30.07.2015/



https://skynet48.ru/wp-content/uploads/2015/08/Advanced-Excel-VBA-Macros.png
283
343

admin

https://skynet48.ru/wp-content/uploads/2017/04/logo_skynet.png

admin2015-07-30 16:43:312018-06-20 11:41:49Экспорт из Excel в XML с помощью макроса на VBA

  1. Importance of an XML Parser
  2. Build XML Parser Using VBA
  3. Conclusion

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.

  • Go to References

  • Scroll down and check Microsoft XML, V6.0, then click on OK.

    Add Microsoft XML V6.0 Reference

    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:

Load the XML File Into XML DOM

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:

use the XML file data to store it in an Excel sheet

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.

Skip to content

VBA code to convert excel to xml

Home » VBA » VBA code to convert excel to xml

We can use VBA to convert and Save the Excel File as XML file. This example macro will help us to know how to convert Excel Worksheet into a XML file format. This can be used in Excel 2003,2007,2010,2013.

vba code to convert excel to XML- Syntax

Here is the example Excel VBA Syntax to convert the Excel to XML format.

Workbook.SaveAs fileName:="filepath to save the csv file", FileFormat:=xlXMLSpreadsheet, ReadOnlyRecommended:=False, CreateBackup:=False

VBA code to Convert and Save the Excel to XML- Example

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.

VBA code to Convert and Save the Excel to XML- Instructions

Please follow the below step by step instructions to test this Example VBA Macro codes:

  • Step 1: Open a New Excel workbook
  • Step 2: Press Alt+F11 – This will open the VBA Editor (alternatively, you can open it from Developer Tab in Excel Ribbon)
  • Step 3: Insert a code module from then insert menu of the VBE
  • Step 4: Copy the above code and paste in the code module which have inserted in the above step
  • Step 5: Change the Workbook name in the code as per your example folder and also change the destination file path as per your requirement
  • Step 6: Now press F5 to execute the code or F8 to debug the Macro to check the macro
Effortlessly Manage Your Projects and Resources
120+ Professional Project Management Templates!

A Powerful & Multi-purpose Templates for project management. Now seamlessly manage your projects, tasks, meetings, presentations, teams, customers, stakeholders and time. This page describes all the amazing new features and options that come with our premium templates.

Save Up to 85% LIMITED TIME OFFER
Excel VBA Project Management Templates
All-in-One Pack
120+ Project Management Templates
Essential Pack
50+ Project Management Templates

Excel Pack
50+ Excel PM Templates

PowerPoint Pack
50+ Excel PM Templates

MS Word Pack
25+ Word PM Templates

Ultimate Project Management Template

Ultimate Resource Management Template

Project Portfolio Management Templates

Related Posts

  • vba code to convert excel to XML- Syntax
  • VBA code to Convert and Save the Excel to XML- Example
    • VBA code to Convert and Save the Excel to XML- Instructions

VBA Reference

Effortlessly
Manage Your Projects

120+ Project Management Templates

Seamlessly manage your projects with our powerful & multi-purpose templates for project management.

120+ PM Templates Includes:
By PNRaoLast Updated: January 19, 2015Categories: VBATags: XML

5 Comments

  1. nanette.willis@nch.com
    August 17, 2017 at 2:23 AM — Reply

    When converting from XLSM to XML are the macros included in the XML?

  2. PNRao
    August 17, 2017 at 3:29 PM — Reply

    No, XML file can not store Macros.

  3. Dilip Shah
    May 24, 2020 at 2:58 PM — Reply

    I think you should first apply your steps first at your end and test how it works. It is not able to generate xml file as suggested.

  4. venu
    June 1, 2020 at 1:39 PM — Reply

    how to set nodes instead of data

  5. Chris P
    October 20, 2020 at 10:03 PM — Reply

    You need to have an existing workbook

Effectively Manage Your
Projects and  Resources

With Our Professional and Premium Project Management Templates!

ANALYSISTABS.COM provides free and premium project management tools, templates and dashboards for effectively managing the projects and analyzing the data.

We’re a crew of professionals expertise in Excel VBA, Business Analysis, Project Management. We’re Sharing our map to Project success with innovative tools, templates, tutorials and tips.

Project Management
Excel VBA

Download Free Excel 2007, 2010, 2013 Add-in for Creating Innovative Dashboards, Tools for Data Mining, Analysis, Visualization. Learn VBA for MS Excel, Word, PowerPoint, Access, Outlook to develop applications for retail, insurance, banking, finance, telecom, healthcare domains.

Analysistabs Logo

Page load link

VBA Projects With Source Code

3 Realtime VBA Projects
with Source Code!

Take Your Projects To The Next Level By Exploring Our Professional Projects

Go to Top

Today I needed to export a table in Excel into an XML format, and here’s the code I whipped up to do it.

All you have to do is select the table range, then run the ExportRangeToXML procedure. You’ll be prompted for a filename and location to save the XML file. You can customise the XML Element names used in the XML structure for the table and rows. The table headers are used for Element names in each row of data.

'*****************************************************
' Purpose:   Exports a selected range (table) to an xml
'            format using table headers.
' Notes:     Requires entry of file name. Uses table headers
'            as Element names for each row.
'
' Developer:        Date:       Description:
' Chris Read        24/04/14    Created.
'*****************************************************
Public Sub ExportRangeToXML()
 
Dim strXML As String
Dim varTable As Variant
Dim intRow As Integer
Dim intCol As Integer
Dim intFileNum As Integer
Dim strFilePath As String
Dim strRowElementName As String
Dim strTableElementName As String
Dim varColumnHeaders As Variant
 
    'Set custom names
    strTableElementName = "Table"
    strRowElementName = "Row"
 
    'Set file path
    strFilePath = Application.GetSaveAsFilename(, "(*.xml),*.xml", , "Save As...")
    If strFilePath = vbNullString Then Exit Sub
 
    'Get table data
    varTable = Selection.Value
    varColumnHeaders = Selection.Rows(1).Value
 
    'Build xml
    strXML = "<!--?xml version=""1.0"" encoding=""utf-8""?-->"
    strXML = strXML &amp; "&lt;" &amp; strTableElementName &amp; "&gt;"
    For intRow = 2 To UBound(varTable, 1)
        strXML = strXML &amp; "&lt;" &amp; strRowElementName &amp; "&gt;"
        For intCol = 1 To UBound(varTable, 2)
            strXML = strXML &amp; "&lt;" &amp; varColumnHeaders(1, intCol) &amp; "&gt;" &amp; _
                varTable(intRow, intCol) &amp; "<!--" & varColumnHeaders(1, intCol) & "-->"
        Next
        strXML = strXML &amp; "<!--" & strRowElementName & "-->"
    Next
    strXML = strXML &amp; "<!--" & strTableElementName & "-->"
 
    'Get next file number
    intFileNum = FreeFile
 
    'Open the file, write output, then close file
    Open strFilePath For Output As #intFileNum
    Print #intFileNum, strXML
    Close #intFileNum
 
End Sub

Download “modExportRangeToXML.bas” modExportRangeToXML.bas – Downloaded 1807 times – 2 KB

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

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"

Like this post? Please share to your friends:
  • Xml from excel 2007
  • Xml from excel 2003
  • Xml format for excel
  • Xml for excel ribbon
  • Xml for excel import