2015-11-05 55 views
0

我的XML文件是這樣的:導入XML文件到Excel中三個不同片

enter image description here

當我導入此文件到Excel中,我得到一個表的內容。然而,我需要爲每個標籤分別使用三個表格:

<Header> 
<MasterFiles> 
<SourceDocuments> 

因爲它們看起來像三個相關的表格。

我使用導入該文件中的代碼是:

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

但如何打破XML文件分成三個部分,並且每個導入到不同的表?

+0

XML中的內容是確定第二件和第三件? – BruceWayne

+1

蠻力:創建3個文件副本,並使用MSXML2.DOMDocument將它們作爲* XML打開,除去需要的所有元素,然後保存XML文件,然後使用「Workbooks.OpenXML」打開XML文件方法.. –

+0

@BruceWayne該文件分爲

,

回答

1

考慮使用XSLT經由VBA的MSXML對象提取從較大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 
+0

謝謝,我試圖添加引用「Microsoft XML,v.6,0」並運行代碼,但它不工作,我猜我需要另一個參考? –

+0

有趣...嘗試Microsoft XML v.3.0。你使用的是Windows還是Mac? – Parfait