Excel VBA可通过MSXML2.DOMDocument60加载、解析和操作XML,需启用Microsoft XML, v6.0引用,支持文件/字符串加载、XPath查询、节点增删改及保存,注意UTF-8编码与错误处理。
Excel VBA 可以通过 MSXML 库(如 MSXML2.DOMDocument60)加载、解析和操作 XML 文件,无需外部依赖,但需注意引用设置和常见编码/格式问题。
在 VBA 编辑器中,点击「工具」→「引用」,勾选:
Microsoft XML, v6.0(推荐,兼容性好、支持 XPath 和 UTF-8)
若未列出,可尝试 v3.0(旧系统)或确认系统已安装 MSXML 6.0。
创建文档对象示例:
Dim xmlDoc As New MSXML2.DOMDocument60 xmlDoc.async = False ' 同步加载,避免读取未完成 xmlDoc.validateOnParse = False ' 可选:跳过 DTD 验证防止报错
支持从本地文件或内存字符串加载:
If Not xmlDoc.Load("C:\data\config.xml") Then MsgBox "加载失败:" & xmlDoc.parseError.reason
xmlDoc.LoadXML "- A
"
⚠️ 注意:路径含中文或特殊字符时,确保文件存在且编码为 UTF-8(无 BOM)或 ANSI;若乱码,可用 ADODB.Stream 先读取再转码。
加载成功后,用 XPath 或遍历方式取值:
Set nodes = xmlDoc.getElementsByTagName("ProductName")For i = 0 To nodes.Length - 1
Debug.Print nodes(i).Text
xmlDoc.setProperty "SelectionLanguage", "XPath"
Set node = xmlDoc.SelectSingleNode("//Order[@status='shipped']/Customer/Name")
If Not node Is Nothing Then Debug.Print node.Text
Set item = xmlDoc.SelectSingleNode("//item")
If Not item Is Nothing Then Debug.Print item.getAttribute("id")VBA 可动态创建或修改节点,再保存回文件:
Set newNode = xmlDoc.createElement("Remark")
newNode.Text = "已核验"
xmlDoc.DocumentElement.appendChild newNodexmlDoc.Save "C:\data\updated.xml"ADODB.Stream 写入并指定 charset。若只需导出部分数据到 Excel 表格,可循环节点,逐行写入 ActiveSheet.Cells(row, col) = node.Text。
不复杂但容易忽略编码和错误处理——加一句 If xmlDoc.ParseError.ErrorCode 0 Then 判断,能省去大半调试时间。