Click here to Skip to main content
Click here to Skip to main content

Export Excel to XML in VBA

By , 3 May 2004
 
Sample Image - xls2xml.jpg

Introduction

In Excel XP, there is a new export option for XML. However, what I get is many rubbish tags (I'm so disappointed...). Then, after searching on the Google (our nice search engine) for some time about "Converting Excel to XML", what I get are conversion tools that simply make a Rational table to XML. However, what I want is the support of nested structures (e.g. <data><field1>....</field1><data>). As a result, I decided to write my own using VBA... (don't ask me why VBA... may be I will port it to my favorite C++ platform later. :)

Using the Code

The source code contains 2 functions GenerateXMLDOM() and fGenerateXML(). They are actually doing the same thing in a different approach.

GenerateXMLDOM -- Gives a Microsoft XMLDOM object which you can play with or serialize into an XML at any time using the "Save" method.

fGenerateXML -- Generates a long string which is ready for output as file (more readable, as proper newline is added).

Both functions have the same parameters. The first one is rngData, which is the selected table area in the Excel Sheet for conversion. The second (rootNodeName) is the first/root node's name used in the XML.

In the selected range, the first row is expected to be the field (or node) names. One thing that is worth noticing is that we can use the node name to define the level it belongs to. Started and separated by the node delimiter "/", the node name is one level deeper than the previous one. e.g. /data/field1 is equivalent to <data><field1>....</field1><data>, /student/name/surname is equivalent to <student><name><surname>.... </surname></name></student>:

'
' rngData : The selected region on Excel sheet, with the first row as field name,
' and data rows below
'  For the field name, use the node delimiter "/" to build the hierarchy of data
'  e.g. /data/field1 is equivalent to <DATA><FIELD1>....</FIELD1><DATA>
'
' rootNodeName : The XML document root node tag name

Function GenerateXMLDOM(rngData As Range, rootNodeName As String)
...


Function fGenerateXML(rngData As Range, rootNodeName As String) As String
...

Limitation and Notes

The ordering of fields may affect the generated XML, fields that have to be placed inside the same sub-node should be placed next to each other. For example, if /student/id and /student/name are placed next to each other, it will generate:

<student><id>..</id><name>...</name></student> 

However, if not, the result will be:

<student><id>..</id></student> <somebrabra...> ... </somebrabra...>
<student><name>..</name></student> 

The reason is that it only checks with the last field instead of all before deciding where the node should be created.

Finally I would like to thank Hasler Thomas, the author of A Filebrowser for VBA, who provided the code for file browse. Hope this code will be useful for you. Please let me know if there are any bugs.

History

  • 4 May 2004 -- First release 0.8 version

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

About the Author

Raymond Pang
Web Developer
Hong Kong Hong Kong
Member
I am fond of programming especially in C++ (but unluckily I know many other different lang.). My special interest is on Graphics and image processing.
 
After graduated from Chinese University of Hong Kong with a research degree about graphics, I starts my career on web programming and games. Please Visit http://www.raybase.com which has software and game projects done by me.

Sign Up to vote   Poor Excellent
Add a reason or comment to your vote: x
Votes of 3 or less require a comment

Comments and Discussions

 
You must Sign In to use this message board.
Search this forum  
    Spacing  Noise  Layout  Per page   
QuestionThanks! Great script!memberVladislav Gasan3 Jan '13 - 0:35 
Thanks! Great script!
QuestionNeed vba code for xml to excelmembersyed mubeen ahmed23 Jun '12 - 9:59 
xml to excle
Questionxml to excelmembersyed mubeen ahmed23 Jun '12 - 9:47 
Hi ,
 
If I have the excel with xml node, can I also put data from xml to excel as per the node.
 
Please provide me a macro for this....
 
Thanks in advance...
QuestionNeed help creating repeating group nodes using this toolmemberDan Gruber1 Sep '11 - 5:12 
Hi is there any way to use this tool to produce repeating groups? I tried to use it to produce the following XML below but I cant get the grades to repeat under the same student node. It creates a new student node for the second grade section. Is there any examples of repeating nodes using this tool? thanks!
 
<?xml version="1.0" ?>
- <data>
- <student>
  <id>1</id>
  <name>Raymond</name>
  <age>11</age>
  <mark>0</mark>
- <grades>
- <grade>
  <score>75</score>
  <letter>C</letter>
  </grade>
- <grade>
  <score>97</score>
  <letter>A</letter>
  </grade>
  </grades>
  </student>
  </data>

Questionloop through all worksheets in a workbook tmemberushasharma198425 Jul '11 - 0:08 
hi
i want to convert 60 worksheets of a workbook to xml so want to know how to loop through worksheets so that all workshhets data gets converted to xml on a single click at the same time. and also there s one problem that find used range function does not work sometime on clicking the button so we get nothing in xml as no text gets selected.
GeneralStill helpful in 2011memberEelze13 Apr '11 - 23:28 
Thanks for this great tool! Microsoft Office 2003 Standard doesn't provide xml functionality. This is a good replacement.
 
Kind regards,
 
Eelze
GeneralEXCEL HELP!!!!memberMRMIG14 Jul '10 - 20:09 
can somebody help me out on the file i am making in excel.
i want to sum two cells by matching item no.
if item no matches then sum the row with the same item no otherwise lookup.
GeneralThanksmemberajalilqarshi6 May '09 - 23:36 
Hi,
Great stuff. Thumbs Up | :thumbsup:
Thanks for sharing.
Ahmad Jalil Qarshi
QuestionChange the default value for rootNodeName [modified]membertasmaniac28 Apr '08 - 13:46 
First of all thanks to the author for this usefull and lifesaver code. In my project I have to use different tag for root other than "" I search a lot in the internet for an explanation but couldn't find any. I'm not a programmer and need help for this.
 
A sample xml document must be look like as below in my project.
 
<Urunler>
<Urun>
<UrunID>271000004</UrunID>
<UrunAdi>Bla Bla Bla </UrunAdi>
<StokAdedi>10</StokAdedi>
<OzelFiyat>100</OzelFiyat>
<Kur>EURO</Kur>
<KDV>18</KDV>
</Urun>
</Urunler>
 
Thanks for help from now.
 
modified on Tuesday, April 29, 2008 2:04 AM

GeneralHelp with VBmemberdommydee@hotmail.com19 Oct '07 - 2:36 
I am wondering if anyone can help me with something very similar to this article in the sense that i am required to capture information in excel then produce an xml file in a pre-defined schema. To capture this information in a pretty form possibly with simple validation with the option to click a publish button then creating the xml file. The xml file would then be fed into a swf file allowing for an offline preview solution based on the users input. This seems a realistic solution but any guidance on this would be much appreciated.
 
Dom
Questionxml conforming to DTDmembermeghz8 May '07 - 0:09 
I have to generate an xml, which conforms to a given DTD, from an excel .
I have used your demo project to simply genearte a xml from an excel. But could you please help to generate a xml conforming to a given DTD.D'Oh! | :doh:
Generalgeneralized conversion to XMLmemberrkapl7 Jan '07 - 10:35 
Hi Raymond!
 
You might be interested in another solution that is able to convert to XML without (almost) any limitations: Table2XML
 
It works by reverting the "flattener" methodology that is applied when Excel loads XML files. With a few changes to column order (and adding/deleting some columns) you have a very flexible way to convert tabular data into XML. The algorithm doesn't need any add-in (as MSXML), so it's easy to rewrite it in any other environment/language (I've already created a perl version here).
 
-regards
 
Roland
GeneralNot support xsdmemberPerlDev6 Oct '06 - 2:39 
I wish to see it supports xsd. i.e. given xsd and selected range, we could get proper xml.
Generalexcel project deploymentmemberfatih isikhan11 Apr '06 - 3:59 

hi,
i wrote a project that takes data from database and saves it as an excel document. i tried to run the project on different computer but without giving any error, it stops running. i copied all the dll files and i have the same framework that i compiled the project.
is there any way to deploy an office 2000 project?
thanks for your concern.
GeneralRe: excel project deploymentmemberPerlDev6 Oct '06 - 2:34 
same os? where did you save the DLLs? are the security settings same?..
GeneralRe: excel project deploymentmemberfatih isikhan6 Oct '06 - 3:21 
Hi,
 
I fix the problem. It was about language incompatibility.
My os was Turkish while the office was in English.
I changed the regional settings to both English and now it works.
GeneralCompile Errormemberslefever1 Dec '05 - 8:07 
Attribute VB_Name = "ConvertXML"
 
I get a compile error once I try to run this.
Any suggestions
GeneralRe: Compile ErrormemberRaymond Pang6 Dec '05 - 5:10 
Hello. May I know what version of Excel you are using ? BTW, can you give more info for the error message you got ?
GeneralRe: Compile ErrormemberDavid Daltonhurst1 Jul '09 - 9:30 
I get the same Compile error for Attribute in Excel 2003 Basic
Generalexport txt to xlsmemberAunalisiraj12 Oct '05 - 22:07 
can u plz tell me how to export text file to excel file. i have to do this in vb6 so plz tell me how i can export tab delimited text file in excel file .
thanks
 
adeel
QuestionAttributes?memberMani Shankar25 Aug '05 - 23:42 
This application is well written, but has the severe limitation of not being able to work with space characters in the tags. This means attributes are out.
 
I'm gonna think about how to fix that, but if you already have answers, let me know
 
M.
AnswerRe: Attributes?memberRaymond Pang27 Aug '05 - 21:20 
Sorry that I didn't get it updated. So, in case that you had fixed it, please let me know Big Grin | :-D Thx.
GeneralAttributes!memberMani Shankar29 Aug '05 - 0:33 
I used a couple of additonal declarations:
 
Dim Attributes() As String 'Array storing the current splited attribute names
Dim Parts() As String
 
After this, I edited some code as below, and it works like a charm!
 
For t = i To UBound(Nodes)
Attributes = Split(Nodes(t), ATTRIBUTE_DELIMITER)
If UBound(Attributes) > 0 Then
Parts = Split(Attributes(1), "=")
End If
' create uncommon nodes with the previous one
'Set new_nodes(t) = ObjXMLDoc.createNode(1, Nodes(t), "")
Set new_nodes(t) = ObjXMLDoc.createNode(1, Attributes(0), "")

If UBound(Attributes) > 0 Then
Dim objAttrib As IXMLDOMAttribute
Set objAttrib = ObjXMLDoc.createAttribute(Parts(0))
Parts = Split(Parts(1), "''")
objAttrib.Text = Parts(0)
new_nodes(t).Attributes.setNamedItem objAttrib
End If

Next
 
Rest of it the same.
 
Cheers,
M.
GeneralRe: Attributes!memberthaylin7928 Nov '06 - 4:40 
I came across this and thought it would be great but for some reason I'm getting an error on the IXMLDOMAttribute Dim. Does excel 2003 not support this? It's so difficult to find any decent info on any MS coding. I figured maybe you could help. I added the code in the GenerateXMLDOM function which I believe is where it should be. It's just giving me the Compile error of User defined type not defined. Any help would be greatly appreciated.
AnswerRe: Attributes?memberkevingreiner10 Jan '06 - 2:02 
I also added support for attributes but I used the other method of generating XML. That is, I modified the function that doesn't use the XML DOM. This gave me a lot control over indenting, which I needed. My code also doesn't output an attribute unless there is a value. I had to modify quite a bit of code to get it working the way I needed.
 
Email me at greinerk@gmail.com if you want a copy.

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Rant Rant    Admin Admin   

Permalink | Advertise | Privacy | Mobile
Web03 | 2.6.130523.1 | Last Updated 4 May 2004
Article Copyright 2004 by Raymond Pang
Everything else Copyright © CodeProject, 1999-2013
Terms of Use
Layout: fixed | fluid