Skip to content

Instantly share code, notes, and snippets.

@atifaziz
Created February 13, 2014 14:57
Show Gist options
  • Star 5 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save atifaziz/8976460 to your computer and use it in GitHub Desktop.
Save atifaziz/8976460 to your computer and use it in GitHub Desktop.
XML pretty printing in VBA
Function PrettyXML(ByVal Source, Optional ByVal EmitXMLDeclaration As Boolean) As String
Dim Writer As MXXMLWriter, Reader As SAXXMLReader
Set Writer = New MXXMLWriter
Writer.indent = True
Writer.omitXMLDeclaration = Not EmitXMLDeclaration
Set Reader = New SAXXMLReader
Set Reader.contentHandler = Writer
Reader.Parse Source
PrettyXML = Writer.Output
End Function
@hendrikbeck
Copy link

Hey, thanks for posting this! When I try this out, Excel stumbles upon line 3 and tells me it doesn't know the type "MXXMLWriter". Is this meant to work in Excel?

Thanks and cheers
Hendrik

@SaintPeter
Copy link

Note: If you are using MSXML 6.0, you need to qualify the declarations with a 6.0 on the end.

Function PrettyXML(ByVal Source, Optional ByVal EmitXMLDeclaration As Boolean) As String
    Dim Writer As MXXMLWriter60, Reader As SAXXMLReader60
    Set Writer = New MXXMLWriter60
    Writer.indent = True
    Writer.omitXMLDeclaration = Not EmitXMLDeclaration
    Set Reader = New SAXXMLReader60
    Set Reader.contentHandler = Writer
    Reader.parse Source
    PrettyXML = Writer.Output
End Function

This worked well for me in Access VBA.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment