通过VBA将XML加载到Excel中

11

我有一段通过 VBA 加载 XML 文件的代码。然而,导入后它全部位于一个列中而不是分成表格。

当我通过“数据”选项卡手动导入时,会出现没有模式的警告,但询问是否要 Excel 基于源数据创建一个模式。这将把所有数据放入一个漂亮的表格中。

我希望在我的当前 VBA 代码中自动完成此操作:

VBA 代码如下:

      Sub refresh()

'--------------------------------1. Profile IDs-----------------------------------'


'date variables

Dim start_period As String
start_period = Sheets("Automated").Cells(1, 6).Value
Dim end_period As String
end_period = Sheets("Automated").Cells(1, 7).Value

'report id variable names
Dim BusinessplanningReportID As String

'--------------------------------REST queries--------------------------------'
Dim Businessplanning As String



'REST query values
Businessplanning = "URL;http://api.trucast.net/2/saved_searches/00000/pivot/content_volume_trend/?apikey=0000000&start=" + start_period + "&end=" + end_period + "&format=xml"




'--------------------------------------------Data connections-----------------------------------'
'key metrics
With Worksheets("Sheet1").QueryTables.Add(Connection:=Businessplanning, Destination:=Worksheets("Sheet1").Range("A1"))

  .RefreshStyle = xlOverwriteCells
  .SaveData = True

End With

目前,数据呈现的是无结构的形式。我该如何自动将其转换为表格?

<result>
<entry>
<published_date>20130201</published_date>
<post_count>18</post_count>
</entry>
感谢您, ::最终解决方案::
 Sub XMLfromPPTExample2()
Dim XDoc As MSXML2.DOMDocument
Dim xresult As MSXML2.IXMLDOMNode
Dim xentry As MSXML2.IXMLDOMNode
Dim xChild As MSXML2.IXMLDOMNode
Dim start_period As String
    start_period = Sheets("Automated").Cells(1, 6).Value
    Dim end_period As String
    end_period = Sheets("Automated").Cells(1, 7).Value
Dim wb As Workbook
Dim Col As Integer
Dim Row As Integer


Set XDoc = New MSXML2.DOMDocument
XDoc.async = False
XDoc.validateOnParse = False
XDoc.Load ("http://api.trucast.net/2/saved_searches/0000/pivot/content_volume_trend/?apikey=00000&start=" + start_period + "&end=" + end_period + "&format=xml")
LoadOption = xlXmlLoadImportToList

Set xresult = XDoc.DocumentElement
Set xentry = xresult.FirstChild


Col = 1
Row = 1

For Each xentry In xresult.ChildNodes
 Row = 1


    For Each xChild In xentry.ChildNodes
      Worksheets("Sheet2").Cells(Col, Row).Value = xChild.Text
             'MsgBox xChild.BaseName & " " & xChild.Text
      Row = Row + 1
      'Col = Col + 1

          Next xChild
'Row = Row + 1
Col = Col + 1
Next xentry

End Sub
2个回答

10

“硬编码”的方式是这样的:

从这里开始

<result>
   <entry>
      <published_date>20130201</published_date>
      <post_count>18</post_count>    
   </entry>
  <entry>
      <published_date>20120201</published_date>
      <post_count>15</post_count>    
   </entry>

你希望获得一个包含两列的 Excel 表格:

**published_date** |  **post_count**
20130201       |           18
20120201       |           15

因此我们可以假设在你的XML中总会有

<result><entry><Element>VALUE</Element><Element...n>VALUE</Element...n></entry>

重要提示: 在PowerPoint、Excel和Word中打开VBA编辑器,添加对“Microsoft XML, v3.0”的引用(此引用适用于Office 2000...您可能有其他版本的引用)。

来源:http://vba2vsto.blogspot.it/2008/12/reading-xml-from-vba.html

Employee.XML

<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<EmpDetails>
<Employee>
<Name>ABC</Name>
<Dept>IT-Software</Dept>
<Location>New Delhi</Location>
</Employee>
<Employee>
<Name>XYZ</Name>
<Dept>IT-Software</Dept>
<Location>Chennai</Location>
</Employee>
<Employee>
<Name>IJK</Name>
<Dept>HR Operations</Dept>
<Location>Bangalore</Location>
</Employee>
</EmpDetails>

阅读上面的XML代码

Sub XMLfromPPTExample()
Dim XDoc As MSXML2.DOMDocument
Dim xEmpDetails As MSXML2.IXMLDOMNode
Dim xEmployee As MSXML2.IXMLDOMNode
Dim xChild As MSXML2.IXMLDOMNode

Set XDoc = New MSXML2.DOMDocument
XDoc.async = False
XDoc.validateOnParse = False
XDoc.Load ("C:\Emp.xml")
Set xEmpDetails = XDoc.documentElement
Set xEmployee = xEmpDetails.firstChild
For Each xEmployee In xEmpDetails.childNodes
For Each xChild In xEmployee.childNodes
MsgBox xChild.baseName & " " & xChild.Text
Next xChild
Next xEmployee
End Sub

针对您的情况,当然需要调整您的例行程序:

在提供的代码中,将 "result" 改为 "EmpDetails"
将 "entry" 改为 "Employee"

还需要进行其他必要的调整。


这样,您就可以拥有任意数量的 "entry" 和 "entry child" 元素。

实际上,遍历 "entry" 元素内的所有元素,您将获得您的表格列,每个新的 "entry" 都是一个新的行。

不幸的是,我没有MAC上的Excel,所以我只是放置了逻辑,您应该检查自己的语法...这样,您可以在想要的工作表上建立一个EXCEL表格。

Dim col = 1; Dim row=1;

For Each xEmployee In xEmpDetails.childNodes
    col = 1
    For Each xChild In xEmployee.childNodes
       Worksheets("NAMEOFTHESHEET").Cells(col, row).Value = xChild.Text
       MsgBox xChild.baseName & " " & xChild.Text
       col = col + 1;
    Next xChild
row = row+1;
Next xEmployee

正确的方式应该是这样的:

LoadOption:=xlXmlLoadImportToList?

您正在通过 URL 调用获取 XML,但我强烈建议开始时尝试使用磁盘上的 XML 文件,并检查其是否正确有效。所以您应该从此“WebService”获取一个样本 XML,然后将其保存到磁盘上。并尝试以以下方式加载它:

   Sub ImportXMLtoList()
    Dim strTargetFile As String
    Dim wb as Workbook

         Application.Screenupdating = False
         Application.DisplayAlerts = False
         strTargetFile = "C:\example.xml"
         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
    End Sub

我不太明白你遇到的问题在哪里。你是否从 Web 服务获取 XML?你能否发布一份从 Web 服务获取的样本 XML?好的,它仍然是空白的,但肯定有原因!你是否在代码中到达了这行:Worksheets("NAMEOFTHESHEET").Cells(col, row).Value = xChild.Text?或者你甚至没有到达这行吗?你可以分享你的 EXCEL 吗? - Madthew
我已经更新了解决方案。你可能需要添加对“Microsoft XML,v3.0”(或适用于你的EXCEL版本的版本)的引用! - Madthew
我按得太快了,还没写完注释就按了回车。它引用了一个现有的表格。 - Fox87
你能检查一下问题是不是 xChild.Text 吗?请尝试使用以下代码:Worksheets("sheet2").Cells(Col, Row).Value = 4 OR Worksheets("sheet2").Cells(Col, Row).Value = '4' 或者 Worksheets("sheet2").Cells(3, 3).Value = 4 OR Worksheets("sheet2").Cells(3, 3).Value = '4',以检查问题是否可能出现在单元格 (0,0) 或许应该从 1 开始。 - Madthew
好的,太棒了。已经搞定了,感谢你的所有帮助。需要将行设置为1。最终的工作解决方案在第一篇帖子中。干杯 :) - Fox87
显示剩余10条评论

0

我使用了一些从其他代码部分中找到的代码。以下代码将提示用户选择要使用的XML文件,并允许他们将所选文件简单地添加/导入到其现有映射中,而无需打开新文件。

Sub Import_XML()
'
' Import_XML Macro
'
    'Select the file
    Fname = Application.GetOpenFilename(FileFilter:="xml files (*.xml), *.xml", MultiSelect:=False)

    'Check if file selected
    If Fname = False Then
        Exit Sub
        Else

    End If

    'Import selected XML file into existing, custom mapping

    Range("B5").Select
    ActiveWorkbook.XmlMaps("Result_file_Map").Import URL:=Fname
End Sub

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接