Home » excel » excel – Create custom XML map

excel – Create custom XML map

Posted by: admin April 23, 2020 Leave a comment

Questions:

I’m trying to create a custom XML map using Excel VBA. My XML file is BookData.xml:

<?xml version='1.0'?>
<BookInfo>
   <Book>
      <ISBN>989-0-487-04641-2</ISBN>
      <Title>My World</Title>
      <Author>Nancy Davolio</Author>
      <Quantity>121</Quantity>
   </Book>
   <Book>
      <ISBN>981-0-776-05541-0</ISBN>
      <Title>Get Connected</Title>
      <Author>Janet Leverling</Author>
      <Quantity>435</Quantity>
   </Book>
   <Book>
      <ISBN>999-1-543-02345-2</ISBN>
      <Title>Honesty</Title>
      <Author>Robert Fuller</Author>
      <Quantity>315</Quantity>
   </Book>
</BookInfo>

and my VBA code in Excel 2013 is:

Sub Create_XSD()
   Dim StrMyXml As String, MyMap As XmlMap
   Dim StrMySchema As String
   StrMyXml = "< BookInfo >"
   StrMyXml = StrMyXml & "<Book>"
   StrMyXml = StrMyXml & "<ISBN>Text</ISBN>"
   StrMyXml = StrMyXml & "<Title>Text</Title>"
   StrMyXml = StrMyXml & "<Author>Text</Author>"
   StrMyXml = StrMyXml & "<Quantity>999</Quantity>"
   StrMyXml = StrMyXml & "</Book>"
   StrMyXml = StrMyXml & "<Book></Book>"
   StrMyXml = StrMyXml & "</ BookInfo >"

   ' Turn off async loading.
   Application.DisplayAlerts = False
   ' Add the string to the XmlMaps collection.
   Set MyMap = ThisWorkbook.XmlMaps.Add(StrMyXml)
   Application.DisplayAlerts = True

   ' Create an empty file and output the schema.
   StrMySchema = ThisWorkbook.XmlMaps(1).Schemas(1).XML
   Open "C:\Documents\MySchema.xsd" For Output As #1
   Print #1, StrMySchema
   Close #1
End Sub

which is returning the error:

Error

On line:

   Set MyMap = ThisWorkbook.XmlMaps.Add(StrMyXml)

I’m trying to understand the logic of how to build custom XML maps using VBA so I can use it on another (more complex) XML file. The code I’m following is here.

So, how to fix this error?

How to&Answers:

Remove the spaces in "</ BookInfo >"

Answer:

You have to remove the comma on line 2 (after Dim StrMyXml As String ) and put the rest of that line in it’s own line with the command Dim in front of it.
It should look like this:

Dim StrMyXml As String

Dim MyMap As XmlMap

Answer:

I have encountered the same error and the response of BruceWayne is fast correct !

I have removed spaces in </ BookInfo > (line 12)
BUT ALSO in < BookInfo > (line 4)

Removing only in </ BookInfo > is not sufficient.