VBA读取XML文件形成二维表并写入到占位符区域

Option Explicit

Sub main()
   Dim xmlfiles, i
   xmlfiles = GetXmlFiles(ThisWorkbook.path & "\Data\*.xml")
   If IsEmpty(xmlfiles) Then Exit Sub
   
   For i = LBound(xmlfiles) To UBound(xmlfiles)
        FillBlock xmlfiles(i)
   Next
   
    
End Sub


Sub FillBlock(xmlfile)
    Dim rep, shtname, blockname, arrc, rCount, cCount
    Dim wb As Workbook, sht As Worksheet, rng0 As Range
    
    Set wb = ThisWorkbook 'Excel.Application.Workbooks.Open(rep)
    
    shtname = Split(xmlfile, ".")(0)
    blockname = Split(xmlfile, ".")(1)
    
    Set sht = wb.Worksheets(shtname)
    sht.Select
    Set rng0 = sht.UsedRange.Find("{" & blockname & "}")
    
    If Not rng0 Is Nothing Then
        rng0.Select
        arrc = getContentArray(xmlfile)
        rCount = UBound(arrc, 1) - LBound(arrc, 1) + 1
        cCount = UBound(arrc, 2) - LBound(arrc, 2) + 1
        rng0.Resize(rCount, cCount) = arrc

    Else
        Debug.Print "no " & blockname
    End If
    
    Set rng0 = Nothing
    Set sht = Nothing
    'wb.Close
    Set wb = Nothing
End Sub


Function GetXmlFiles(pattern As String)
    'traverse data xml
    Dim file, arr, coll, i
    'pattern =
    file = Dir(pattern)
    
    If file = "" Then
        Exit Function
    End If
    
    Set coll = New Collection
    Do While file <> ""
        coll.Add file
        file = Dir
    Loop
     
    ReDim arr(0 To coll.Count - 1)
    For i = 0 To coll.Count - 1
        arr(i) = coll(i + 1)
    Next
    Set coll = Nothing
    GetXmlFiles = arr
End Function

Function getContentArray(xmlfile)
    Dim path, doc, fullname, root, nodes, i, j, columnsCount, rowsCount, arrTitle, arrContent

    path = ThisWorkbook.path & "\Data"
    fullname = path & "\" & xmlfile

    Set doc = CreateObject("Microsoft.XMLDOM")
    doc.Load fullname
    
    Set nodes = doc.SelectNodes("//xs:sequence/xs:element")
    columnsCount = nodes.Length
    For i = 0 To columnsCount - 1
        'Debug.Print nodes(i).getAttribute("name")
    Next
    Set nodes = Nothing

    Set root = doc.DocumentElement
    rowsCount = root.ChildNodes.Length - 1

    ReDim arrContent(0 To rowsCount - 1, 0 To columnsCount - 1)

    For i = 1 To root.ChildNodes.Length - 1 'rowcount已经减过1了
        For j = 0 To columnsCount - 1
           arrContent(i - 1, j) = root.ChildNodes(i).ChildNodes(j).Text
        Next
    Next

    Set doc = Nothing
    
    getContentArray = arrContent
End Function

 

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值