将XML文件导入Excel中,分为三个部分

时间:2015-11-05 18:58:16

标签: xml excel vba excel-vba

我的XML文件如下所示:

enter image description here

当我将此文件导入Excel时,我会得到一个包含其内容的表。但是,我需要为每个标记分别使用三个表:

strTargetFile = "C:\SAFT.xml"
Set wb = Workbooks.OpenXML(Filename:=strTargetFile, LoadOption:=xlXmlLoadImportToList)
wb.Sheets(1).UsedRange.Copy ThisWorkbook.Sheets("Sheet2").Range("A1")

因为它们看起来像三个相关的表。

我用来导入文件的代码是:

carousel-caption

但是如何将XML文件分成三个部分并将每个文件导入另一个工作表?

1 个答案:

答案 0 :(得分:1)

考虑通过VBA的MSXML对象使用XSLT将较大的XML节点提取到单独的XML文件中,并将这三个节点分别导入到不同的工作簿中:

XSLT (嵌入在选择节点更改的宏下面)

<?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
 <xsl:output omit-xml-declaration="yes" indent="yes"/>
 <xsl:strip-space elements="*"/>

  <xsl:template match="*">   
      <xsl:copy-of select="Header"/>       
  </xsl:template>

</xsl:stylesheet>

Excel宏

Sub ExtractData()
On Error GoTo ErrHandle

    Dim xmlDoc As New MSXML2.DOMDocument, xslDoc As New MSXML2.DOMDocument, newDoc As New MSXML2.DOMDocument
    Dim nodeArray As Variant, item As Variant
    Dim wb As Workbook

    nodeArray = Array("Header", "MasterFiles", "SourceDocuments")

    ' LOADING ORIGINAL XML FILE '
    xmlDoc.Load ActiveWorkbook.Path & "\Audit.xml"

    For Each item In nodeArray

        ' LOADING EMBEDDED STRING XSLT DYNAMICALLY SELECTING NODE '
        xslDoc.LoadXML "<?xml version=" & Chr(34) & "1.0" & Chr(34) & " encoding=" & Chr(34) & "UTF-8" & Chr(34) & "?>" _
                        & "<xsl:stylesheet version=" & Chr(34) & "1.0" & Chr(34) & "" _
                        & " xmlns:xsl=" & Chr(34) & "http://www.w3.org/1999/XSL/Transform" & Chr(34) & ">" _
                        & "<xsl:output omit-xml-declaration=" & Chr(34) & "yes" & Chr(34) & " indent=" & Chr(34) & "yes" & Chr(34) & "/>" _
                        & "<xsl:strip-space elements=" & Chr(34) & "*" & Chr(34) & "/>" _
                        & "<xsl:template match=" & Chr(34) & "*" & Chr(34) & ">" _
                        & "<xsl:copy-of select=" & Chr(34) & item & Chr(34) & "/>" _
                        & "</xsl:template>" _
                        & "</xsl:stylesheet>"

        ' TRANSFORMING ORIGINAL XML '
        xmlDoc.transformNodeToObject xslDoc, newDoc

        ' OUTPUTTING TRANSFORMED SMALLER XML FILES '
        newDoc.Save ActiveWorkbook.Path & "\" & item & ".xml"

        ' OPENING EACH XML FILE INTO WORKBOOK '
        Set wb = Workbooks.OpenXML(Filename:=ActiveWorkbook.Path & "\" & item & ".xml", LoadOption:=xlXmlLoadImportToList)

    Next item

    MsgBox "Successfully transformed and loaded XML files!", vbInformation

    Set wb = Nothing
    Exit Sub

ErrHandle:
    MsgBox Err.Number & " - " & Err.Description, vbCritical
    Exit Sub

End Sub