vbamsxmladdattribute

Add attribute to IXMLDOMNode


I am getting Run-time error 438: Object Doesnot support this propoerty or method in the xNamedNodeMap.setNamedItem (myNode) line of the following code:

Sub appendChild()
    Dim xDoc As MSXML2.DOMDocument60
        Set xDoc = New MSXML2.DOMDocument60
        xDoc.LoadXML ("<root><child/></root>")
    Dim myNode As MSXML2.IXMLDOMNode
       Set myNode = xDoc.createNode(2, "Sci-Fi", "")
    Dim xNamedNodeMap As MSXML2.IXMLDOMNamedNodeMap
    Set xNamedNodeMap = xDoc.DocumentElement.ChildNodes.Item(0).Attributes
    xNamedNodeMap.setNamedItem (myNode)
    Debug.Print xDoc.XML
End Sub

Can someone help me to debug the issue?


Solution

  • Remove the parentheses from (myNode)

    xNamedNodeMap.setNamedItem myNode
    

    You should not use parentheses when calling a method unless that method returns a value (and you wish to assign the return value to something). Otherwise, the () cause VBA to evaluate the contained argument, and pass in the result of that evaluation instead of (eg) myNode

    What happens when the argument you're passing is evaluated depends on what type of variable it is, and if it's an object whether that object has a default method/property.

    Objects without a default method/property will raise a runtime error as you are seeing in your code.

    Note - things are different when you're using Call but general advice here is don't use Call...