excel - 如果不存在,如何创建具有特定值的属性 - VBA

标签 excel vba

抱歉我的英语不好,但我会尽力正确描述我的问题。我有一个VBA代码。这是:

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

问题是 - 仅当元素“Operation”不存在时,如何创建值为“UL”的属性“Client”? 这是我使用的 .xml 文件示例:

<?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>

谢谢!

最佳答案

尝试读取属性节点,如果不存在则创建它:

For Each node In oAttributes

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

您当前的代码似乎希望所有元素都具有 Client=UL,以简单地实现这一点:

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

这将根据需要覆盖或创建属性。

关于excel - 如果不存在,如何创建具有特定值的属性 - VBA,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53172131/

相关文章:

.net - 生成Excel文件错误

sql - MS Excel - 现有连接字符串对应于哪个数据表

vba - 选择在 Excel 宏中具有值的列(VBA 中的范围对象)

excel - 用于从 Excel 更新/创建新记录到 Access 的 VBA 代码

vba - 计算列中值的数量(值是文本格式的数字)

excel - 如果 Find 没有按预期工作

vba - 如何使用 XMLHTTP 从网页获取信息

excel - 使用 Charcter().Insert 格式化单元格中的文本片段 (VBA)

Excel VBA 从超链接列表中提取 Web 数据

performance - Excel vba 执行时间与单元格内容长度呈指数关系