使用 ADO MSPersist 提供者開啟 XML 檔案為 Recordset,再用 CopyFromRecordset 批量寫入工作表。
Sub ImportXMLToSheet()
Dim rst As New ADODB.Recordset
Dim stCon As String, stFile As String
Dim j As Long
stFile = "C:\Exports\Report.xml" ' XML 檔案完整路徑
stCon = "Provider=MSPersist;" ' XML 持久化提供者
With rst
.CursorLocation = adUseClient
.Open stFile, stCon, adOpenStatic, adLockReadOnly, adCmdFile
Set .ActiveConnection = Nothing ' 斷開連線,游標獨立
End With
With ActiveSheet
' 寫入欄位名稱(標題列)
For j = 0 To rst.Fields.Count - 1
.Cells(1, j + 1).Value = rst.Fields(j).Name
Next j
' 批量寫入資料(從 A2 開始)
.Range("A2").CopyFromRecordset rst
End With
rst.Close
Set rst = Nothing
MsgBox "XML 匯入完成,共 " & rst.RecordCount & " 筆資料"
End Sub
| 步驟 | 說明 |
|---|---|
| Provider=MSPersist | 專門讀取 ADO 持久化格式(XML/ADTG)的提供者 |
| adCmdFile | 指定來源為檔案而非 SQL 指令 |
| Set ActiveConnection = Nothing | 將 Recordset 變為離線游標,不需維持連線即可操作資料 |
| CopyFromRecordset | 高效批量寫入,自動對應欄位順序,比逐列寫入快數百倍 |
| Fields(j).Name | 取得 XML 中的欄位名稱(屬性名)寫入標題列 |
adPersistXML 產生的標準格式(含 <s:Schema> 結構描述區)。MSXML2.DOMDocument 解析,不可用此法。On Error GoTo ErrHandler
' ... 主程式碼 ...
Exit Sub
ErrHandler:
MsgBox "匯入失敗:" & Err.Description
If rst.State = adStateOpen Then rst.Close
Set rst = Nothing
End Sub