VBA将Excel转为XML的代码
时间: 2024-05-15 14:18:27 浏览: 15
关于将Excel转为XML的VBA代码,您可以尝试以下代码:
```
Sub Export_XML()
'定义变量
Dim xmlDoc As Object
Dim xmlRoot As Object
Dim xmlRec As Object
Dim xmlField As Object
Dim i As Integer, j As Integer
Set xmlDoc = CreateObject("MSXML2.DOMDocument")
'创建XML文档根节点
Set xmlRoot = xmlDoc.createElement("Workbook")
xmlDoc.appendChild xmlRoot
'创建Worksheet节点
For i = 1 To Worksheets.Count
Set xmlRec = xmlDoc.createElement("Worksheet")
xmlRoot.appendChild xmlRec
xmlRec.setAttribute "Name", Worksheets(i).Name
'创建Row节点
For j = 1 To Worksheets(i).UsedRange.Rows.Count
Set xmlField = xmlDoc.createElement("Row")
xmlRec.appendChild xmlField
'创建Cell节点
For k = 1 To Worksheets(i).UsedRange.Columns.Count
Set xmlChild = xmlDoc.createElement("Cell")
xmlField.appendChild xmlChild
xmlChild.setAttribute "Column", k
xmlChild.Text = Worksheets(i).Cells(j, k)
Next k
Next j
Next i
'保存文件
xmlDoc.Save "C:\Test.xml"
'释放对象
Set xmlDoc = Nothing
Set xmlRoot = Nothing
Set xmlRec = Nothing
Set xmlField = Nothing
End Sub
```
这个代码将会把当前打开的Excel文件中所有的sheet转换为XML文件,文件路径为"C:\Test.xml",您可以根据自己的需要进行修改。
相关推荐
![exe](https://img-home.csdnimg.cn/images/20210720083343.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)