使用VBA另存为XML?

时间:2012-03-04 19:18:03

标签: xml excel vba excel-vba

有没有办法将Excel表保存为XML?我有XML Schema文件......以及表中的一些数据......我在Excel中有Save as XML file选项,但是我可以将文件从VBA保存为XML吗?我想自动化一个过程,但我没有找到任何关于此选项的信息。谢谢!

2 个答案:

答案 0 :(得分:5)

好的ol'宏录像机这次救了我:))(为什么我在发布之前没用过它?) 所以... 要加载xml架构,您需要:

ActiveWorkbook.XmlMaps.Add("Book2.xml", "raport").Name _
        = "raport_Map"

并将其保存为xml:

ActiveWorkbook.SaveAsXMLData Filename:="Book3.xml", _
        Map:=ActiveWorkbook.XmlMaps("raport_Map")

谁会想到这很容易?

答案 1 :(得分:0)

这个链接对我帮助最大 - > http://curiousmind.jlion.com/exceltotextfile

链接上的脚本:

Sub MakeXML(iCaptionRow As Integer, iDataStartRow As Integer, sOutputFileName As String)
    Dim Q As String
    Q = Chr$(34)

    Dim sXML As String

    sXML = "<?xml version=" & Q & "1.0" & Q & " encoding=" & Q & "UTF-8" & Q & "?>"
    sXML = sXML & "<rows>"


    ''--determine count of columns
    Dim iColCount As Integer
    iColCount = 1
    While Trim$(Cells(iCaptionRow, iColCount)) > ""
        iColCount = iColCount + 1
    Wend

    Dim iRow As Integer
    iRow = iDataStartRow

    While Cells(iRow, 1) > ""
        sXML = sXML & "<row id=" & Q & iRow & Q & ">"

        For icol = 1 To iColCount - 1
           sXML = sXML & "<" & Trim$(Cells(iCaptionRow, icol)) & ">"
           sXML = sXML & Trim$(Cells(iRow, icol))
           sXML = sXML & "</" & Trim$(Cells(iCaptionRow, icol)) & ">"
        Next

        sXML = sXML & "</row>"
        iRow = iRow + 1
    Wend
    sXML = sXML & "</rows>"

    Dim nDestFile As Integer, sText As String

    ''Close any open text files
    Close

    ''Get the number of the next free text file
    nDestFile = FreeFile

    ''Write the entire file to sText
    Open sOutputFileName For Output As #nDestFile
    Print #nDestFile, sXML
    Close
End Sub

Sub test()
    MakeXML 1, 2, "C:\Users\jlynds\output2.xml"
End Sub