Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to create an attribute with specific value if it doesn't exist - VBA

Tags:

excel

vba

Sorry for my bad English, but i'll try to describe my problem right. I have a code in VBA. Here it is:

Sub TestXML()
Dim doc As New DOMDocument
    Const filePath As String = "D:\Test3.xml"
    Dim isLoaded As Boolean

    isLoaded = doc.Load(filePath)

    If isLoaded Then
        Dim oAttributes As MSXML2.IXMLDOMNodeList
        Set oAttributes = doc.getElementsByTagName("Operation")

        Dim attr As MSXML2.IXMLDOMAttribute
        Dim node As MSXML2.IXMLDOMElement
        Dim tdate As String
        tdate = Format(Now(), "yyyy-mm-dd")
        For Each node In oAttributes
            For Each attr In node.Attributes
                If attr.Name = "Client" Then
                 If attr.Value <> "UL" Then
                    attr.Value = "UL"
                    End If
                ElseIf attr.Name = "Date" Then
                    If attr.Value <> "tdate" Then
                    attr.Value = tdate
                End If
                End If
            Next attr
        Next node

        doc.Save filePath

    End If
End Sub

Question is - How can i create attribute "Client" with value "UL" in element "Operation" only if it doesn't exist? Here is a .xml file example with which i working:

<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<Document>
    <Operations>
        <Operation Date="2018-11-06" Client="UL"/>
        <Operation Date="2018-11-06" Client="UL"/>
        <Operation Date="2018-11-06"/>
    </Operations>
</Document>

Thanks!

like image 398
Nik Ponomaryov Avatar asked Dec 11 '25 15:12

Nik Ponomaryov


1 Answers

Try to read the attribute node, if it does not exist create it:

For Each node In oAttributes

    If (node.getAttributeNode("Client") Is Nothing) Then
        '// add missing attrib
        node.setAttribute "Client", "UL"
    End If

Your current code seems to want all elements to have Client=UL, to accomplish that simply:

For Each node In oAttributes
    node.setAttribute "Client", "UL"
Next node

Which will overwrite or create the attribute as needed.

like image 66
Alex K. Avatar answered Dec 13 '25 09:12

Alex K.



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!