Vba-Excel:将Excel工作表导出为XML?

时间:2013-02-02 06:19:58

标签: xml excel vba

我需要将Excel电子表格数据导出到XML。为此,我在WorkSheet_Activate中添加了几行代码,即

Private Sub Worksheet_Activate()

 Dim oMyconnection As Connection
 Dim oMyrecordset As Recordset
 Dim oMyXML As DOMDocument
 Dim oMyWorkbook As String

 Set oMyconnection = New Connection
 Set oMyrecordset = New Recordset
 Set oMyXML = New DOMDocument

 oMyWorkbook = Application.ThisWorkbook.FullName

 oMyconnection.Open "Provider=Microsoft.Jet.OLEDB.4.0;" & _
                  "Data Source=" & oMyWorkbook & ";" & _
                  "Extended Properties=excel 8.0;" & _
                  "Persist Security Info=False"

 oMyrecordset.Open "Select * from [Sheet1$A1:C100]", oMyconnection, adOpenStatic

 oMyrecordset.Save oMyXML, adPersistXML

 oMyXML.Save (ThisWorkbook.Path & "\Output.xml")

 oMyrecordset.Close
Set oMyconnection = Nothing
Set oMyrecordset = Nothing
Set oMyXML = Nothing

但是当我尝试执行它时,我收到的错误如User-Defined Datatype not found。实际上我因为行Dim oMyXML As DOMDocument而收到此错误。我错过了任何参考?非常感谢任何帮助。

2 个答案:

答案 0 :(得分:1)

我知道这个帖子已经有几个月了,但是您需要添加对“ Microsoft XML,v6.0 ”(或者您拥有/需要的任何版本)的引用来使用DOMDocument数据类型。

Dim oMyXML As MSXML.DOMDocument
Set oMyXML = New MSXML.DOMDocument

答案 1 :(得分:0)

问题本身并不是“XML输出”,而是微软VBA的怪异并引用了正确的ActiveX组件。

查看其中一个/两个链接,看看它们是否有帮助: