用于XML数据修改的Excel宏

时间:2013-07-12 17:47:06

标签: xml excel vba excel-vba

我正在寻找生成一个excel宏,并希望得到一些方向。我要做的是从5个XML文件中获取数据并将它们放入新工作簿中,然后以线图格式绘制结果数据。所有5个文件中的XML文件中的数据都相同,格式如下:

<Sample Secs="25313">
    <Pout>215280</Pout>
</Sample>
<Sample Secs="25562">
    <Pout>233627</Pout>
</Sample>

当在Excel中作为XML表打开时,显示为:

25313   215280
25562   233627

分别带有“Secs”和“Pout”的标题。 “Secs”列在A列中的所有5个文件之间是通用的,然后唯一数据位于列B中的“Pout”列中。对于B列,每个文件中将有大约1500个数据点。我想要完成的是打开所有5个XML文件,从每个文件中提取唯一数据,然后绘制数据。在绘图之前,我希望新的Excel工作簿看起来像这样格式化:

Secs  Pout1  Pout2  Pout3  Pout4  Pout5

“Secs”的数据来自5个文件中的任何一个(通常),B列数据放在相应的Pout#列中。

有没有办法让Excel VBA执行此操作以及我将如何设置它?

1 个答案:

答案 0 :(得分:0)

有关详细信息,请参阅this MSDN page

 Option Explicit

    Private Sub LoadXmlData()

    Dim xmlDoc As New DOMDocument60
    Dim sSecs As String, sPout As String
    Dim iNodes As Integer, i As Integer, t As Integer
    Dim sPath1 As String, sPath2 As String, sPath3 As String, _
        sPath4 As String, sPath5 As String, sTempPath As String

    Range("A1").Value2 = "Secs"
    'Set the file paths of your xml documents here

    sPath1 = ""
    sPath2 = ""
    sPath3 = ""
    sPath4 = ""
    sPath5 = ""

    For t = 0 To 4
        Select Case t
            Case 0
                sTempPath = sPath1
            Case 1
                sTempPath = sPath2
            Case 2
                sTempPath = sPath3
            Case 3
                sTempPath = sPath4
            Case 4
                sTempPath = sPath5
        End Select

        xmlDoc.Load (sTempPath)
        iNodes = xmlDoc.DocumentElement.ChildNodes.Length

        'Fill in the first column with the values from the attribute Secs
        'Only do it once because the values are the same in each file
        If t = 0 Then
            For i = 0 To iNodes - 1
                Range("A" & i + 2).Value2 = xmlDoc.DocumentElement.ChildNodes.Item(i).Attributes.Item(0).Text
            Next i
        End If

        'Fill in the Pout column
        Cells(1, t + 1).Value2 = "Pout" & t + 1
        For i = 0 To iNodes - 1
            Cells(i + 2, t + 1).Value2 = xmlDoc.DocumentElement.ChildNodes.Item(i).nodeTypedValue
        Next i
    Next t

End Sub