VBA将Excel转为XML
时间: 2023-11-11 18:07:10 浏览: 122
通过vba批量将Excel转为PDF
好的,您可以使用VBA代码将Excel文件转换为XML格式。首先,您需要打开Excel文件,并选择您想要转换的工作表。然后,请打开Visual Basic Editor,并输入以下代码:
Sub ExportToXML()
Dim xmlDoc As Object
Dim xmlRoot As Object
Set xmlDoc = CreateObject("Msxml2.DOMDocument")
Set xmlRoot = xmlDoc.createElement("root")
xmlDoc.appendChild xmlRoot
' Set up mapping
Dim map(1 To 2, 1 To 2) As String
map(1, 1) = "Name"
map(1, 2) = "name"
map(2, 1) = "Age"
map(2, 2) = "age"
' Loop through rows
Dim r As Long
Dim c As Long
Dim n As Long
n = Cells(Rows.Count, 1).End(xlUp).Row
For r = 2 To n
' Add row element
Dim xmlRow As Object
Set xmlRow = xmlDoc.createElement("row")
xmlRoot.appendChild xmlRow
' Loop through columns
For c = 1 To 2
' Add column element
Dim xmlColumn As Object
Set xmlColumn = xmlDoc.createElement(map(c, 2))
xmlRow.appendChild xmlColumn
' Add column value
xmlColumn.Text = Cells(r, c).Value
Next c
Next r
' Save as XML file
xmlDoc.Save "C:\example.xml"
End Sub
请根据您的实际情况修改代码中的路径和工作表名称。然后,运行这段代码将Excel文件转换为XML文件。
阅读全文