我可以使用 VBA 中的变量更新 XML 节点值吗
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/17042869/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Can I update an XML node value using a variable in VBA
提问by barryleajo
I am a complete newcomer to learning about XML but OK with VBA in Excel 2010.
我是学习 XML 的新手,但在 Excel 2010 中使用 VBA 还可以。
In Excel VBA I have created a simple CustomXMLPart
with 5 nodes under a single root, akin to the example below:
在 Excel VBA 中,我CustomXMLPart
在单个根目录下创建了一个简单的 5 个节点,类似于下面的示例:
<
<RefTest>
<sRef1>SomeText</sRef1> 'text
<sRef2>XYZ234</sRef2> 'text
<sRef3>ABC123</sRef3> 'text
<dRef4>25/02/1953</dRef4> 'date or text?
<iRef5>0</iRef5> 'numeric or text?
</RefTest>
>
This works OK and I can read the values back-in using VBA.
这工作正常,我可以使用 VBA 重新读取值。
My problem is that the node values (at the moment) are entered as literals (text and digits).
我的问题是节点值(目前)作为文字(文本和数字)输入。
I want to be able to update these node values, from within Excel VBA, but using the contents of VBA variables.
我希望能够从 Excel VBA 中更新这些节点值,但使用 VBA 变量的内容。
So, for example a user enters a value into a userform
text box, into a variable (say MyVar
), and I want to update the node value with the contents of this variable.
A sort of "update node iRef5 with MyVar".
I can find very little reference to Updating XML values like this, especially using variables, on the web.
因此,例如,用户将一个值输入到一个userform
文本框中,一个变量(比如MyVar
)中,我想用这个变量的内容更新节点值。一种“使用 MyVar 更新节点 iRef5”。我在网上几乎找不到像这样更新 XML 值的参考,尤其是使用变量。
Can this be done from within VBA? If so, what is the approach, how does XML deal with variables, and perhaps an example of the exact syntax please.
这可以在 VBA 中完成吗?如果是这样,方法是什么,XML 如何处理变量,也许是确切语法的示例。
With all thanks in anticipation.
感谢所有的期待。
回答by MiVoth
I don't know what structure of your xml will have. But if it's only these five nodes, perhaps something like this might help you:
我不知道你的 xml 会有什么结构。但如果只有这五个节点,也许这样的事情可能会帮助你:
Sub XMLTest()
Dim myVar As String, pathToXML As String
Dim xmlDoc As Object, xmlRoot As Object
Set xmlDoc = CreateObject("MSXML2.DOMDocument")
pathToXML = "N:\example.xml" '<--- change the path
Call xmlDoc.Load(pathToXML)
Set xmlRoot = xmlDoc.getElementsByTagName("RefTest").Item(0)
myVar = "foobar" '<--- your value
xmlRoot.selectSingleNode("iRef5").Text = myVar
Call xmlDoc.Save(pathToXML)
End Sub
If this doesn't help you, you should give more information about your xml and what you actually want to do.
如果这对您没有帮助,您应该提供有关您的 xml 以及您实际想要做什么的更多信息。