0

I need to update a "simple" XML file with new values and save with a new name. For a test I am only trying to update one value. But using the code below I get an error:

Run-time error '91': Object variable or With block variable not set

VBA:

Sub XMLTest()
Dim myVar As String, pathToXML As String
Dim xmlDoc As Object, xmlRoot As Object
    Set xmlDoc = CreateObject("MSXML2.DOMDocument")
    pathToXML = "C:\Users\Path_to_XML\PJMeasurements.xml" '<--- Update path

    Call xmlDoc.Load(pathToXML)
    Set xmlRoot = xmlDoc.getElementsByTagName("ns0:MeasurementsSO").Item(0) '<--- Is this correct?
    myVar = "9999-9999999" '<--- Update value
    xmlRoot.SelectSingleNode("SalesOrderNo").Text = myVar

    Call xmlDoc.Save(pathToXML)
End Sub

This is the XML:

<ns0:MeasurementsSO xmlns:ns0="http://update.DocumentTypes.Schema.PJ Measurement.Xml">
  <SalesOrderNo>23482-4612310</SalesOrderNo>
  <Weight>83</Weight>
  <Volume>0,03</Volume>
  <Numberofcolli>1</Numberofcolli>
</ns0:MeasurementsSO>
1
  • I guess, there's extra space in the namespace PJ Measurement.Xml? Commented May 27, 2020 at 7:53

2 Answers 2

1

You need to add namespace:

Sub XMLTest()
    Dim myVar As String, pathToXML As String
    Dim xmlDoc As Object, xmlNode As Object
    Set xmlDoc = CreateObject("MSXML2.DOMDocument")
    pathToXML = "C:\Temp\PJMeasurements.xml" '<--- Update path
    xmlDoc.setProperty "SelectionNamespaces", "xmlns:ns0='http://update.DocumentTypes.Schema.PJMeasurement.Xml'"
    Call xmlDoc.Load(pathToXML)
    Set xmlNode = xmlDoc.SelectSingleNode("/ns0:MeasurementsSO/SalesOrderNo")
    myVar = "9999-9999999" '<--- Update value
    xmlNode.Text = myVar
    Call xmlDoc.Save(pathToXML)
End Sub
Sign up to request clarification or add additional context in comments.

2 Comments

Oh, i didnt see your reply. I found an solution myself by updating GetElementsByTagName from: MeasurementsSO to ns0:MeasurementsSO. Is your solution more correct?
@Gjeep 1) You didn't add namespace. 2) It selects the element you need in one step 😉
0

Found the error my self.

GetElementsByTagName was wrong.

Updated above.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.