使用VBA导入XML。每个标记行在单独的单元格上

时间:2017-01-20 13:33:38

标签: xml excel vba excel-vba import

我目前正在尝试编写一些将XML文件导入电子表格的VBA。我现在有下面的内容,但是,所有XML都进入一个单元格。无论如何我可以让每个标签进入一个单独的单元格吗? (见附图)

Ideal Macro

Dim filter As String 
Dim caption As String
Dim Filename As String 
Dim Overall As Workbook 
Dim targetWorkbook As Workbook

    Set targetWorkbook = Application.ActiveWorkbook

    filter = "Text files (*.xml),*.xlsm " caption = "Please Select an input file " Filename = Application.GetOpenFilename(filter, , caption)

    Set Overall = Application.Workbooks.Open(Filename)

         Set wb = Workbooks.OpenXML(Filename:=strTargetFile, LoadOption:=xlXmlLoadImportToList)
         Application.DisplayAlerts = True

         wb.Sheets(1).UsedRange.Copy ThisWorkbook.Sheets("Sheet2").Range("A1")
         wb.Close False
         Application.ScreenUpdating = True
         Overall.Close

1 个答案:

答案 0 :(得分:0)

如果您的XML文件在每个XML标记之后使用适当的新行格式化,那么应该这样做:

  Dim fso As New Scripting.FileSystemObject

  Dim xmlFile As Scripting.File
  Set xmlFile = fso.GetFile(Filename)

  Dim ts As Scripting.TextStream
  Set ts = xmlFile.OpenAsTextStream(ForReading)

  Dim i As Long: i = 2
  Dim ws as Worksheet
  Set ws = Workbooks("OutputWorkbook").Worksheets("OutputSheet")

  While Not ts.AtEndOfStream
        ws.Cells(i, 1).Value = ts.ReadLine
        i = i + 1
  Wend

  ts.Close
  Set ts = Nothing

需要引用Microsoft Scripting Runtime,您可能需要调整整体代码以将文本放在您需要的位置...