Adding attribute to xml custompart in docx Word document at run time using VBA

Posted on 2014-08-07
Last Modified: 2016-05-12
I am saving data included in Word document in XML format in the ActiveDocument.CustomXmlParts.
I can add node to the XML structure, using VBA code,  but I didn't succeed to add new attribute. I've search a lot but didn't find any reference to this.
Here is the code:

Set MyDoc = ActiveDocument
xml = "<Root><Cities><City id='1'>NY</City><City id='2'>Boston</City></Cities></Root>"
Set MyPart = MyDoc.CustomXMLParts.Add(xml)
Set ParentNode = MyPart.SelectSingleNode("//Root/Cities")
MyPart.AddNode ParentNode, "City", , , , "LA"

Open in new window

How to add a node at runtime with an attribute: <City id='3'>LA</City>

Thank you

Question by:nava1000
    LVL 35

    Accepted Solution

    I'm not really able to test this other than in the VBA editor with a watch, but this seems to work:

    After your line 6 (I added the code block above), add this line:
    MyPart.AddNode ParentNode.LastChild, "id", , , msoCustomXMLNodeAttribute, 3

    Open in new window


    Author Comment

    Thank you very much.

    Featured Post

    Looking for New Ways to Advertise?

    Engage with tech pros in our community with native advertising, as a Vendor Expert, and more.

    Join & Write a Comment

    Suggested Solutions

    Everything You've Ever Assumed Is Wrong The average IT professional has a misunderstanding of what customers really want. They mistakenly think that when a computer breaks, contracts a virus, or has other issues, the customer wants that issue “fixe…
    There are many benefits to finding online courses that align with your personal or career goals. Read more about our reasons for continuing your education in technology.
    In this sixth video of the Xpdf series, we discuss and demonstrate the PDFtoPNG utility, which converts a multi-page PDF file to separate color, grayscale, or monochrome PNG files, creating one PNG file for each page in the PDF. It does this via a c…
    Excel styles will make formatting consistent and let you apply and change formatting faster. In this tutorial, you'll learn how to use Excel's built-in styles, how to modify styles, and how to create your own. You'll also learn how to use your custo…

    745 members asked questions and received personalized solutions in the past 7 days.

    Join the community of 500,000 technology professionals and ask your questions.

    Join & Ask a Question

    Need Help in Real-Time?

    Connect with top rated Experts

    18 Experts available now in Live!

    Get 1:1 Help Now