簡體   English   中英

如何通過VBA將某些XML數據讀入Excel

[英]How read certain XML data into Excel via VBA

我從Google Map Distance Matrix API獲得了XML響應文本,我必須將其讀入Excel或從XML響應文本中發出某些信息。 我只需要在值<Status><Text>的持續時間和<Text>的距離。

這是我的VBA代碼:

Sub Button1_Click()
Dim x As Long, y As Long
Dim htm As Object
Dim wb As Workbook
Dim ws As Worksheet
Dim TxtRng  As Range

Dim num1 As String

Set wb = ActiveWorkbook
Set ws = wb.Sheets("Sheet1")

Set htm = CreateObject("htmlFile")
num1 = Cells(2, 2).Value

With CreateObject("msxml2.xmlhttp")
    .Open "GET", "https://maps.googleapis.com/maps/api/distancematrix/xml?origins=sy8 2jp&destinations=" & num1 & "&mode=driving&language=en-GB&v=3&sensor=false&units=imperial", False
    .send
    htm.body.innerHTML = .responseText
    Debug.Print .responseText (don't know how to debug print certain value)

    MSGbox (.responseText)(or strip out certain value of response text)
End With

End Sub

這是我的調試打印響應文本

 <status>OK</status>
 <origin_address UK</origin_address>
 <destination_address>UK</destination_address>
 <row>
  <element>
    <status>OK</status>
      <duration>
      <value>622</value>
      <text>10 mins</text>
      </duration>
   <distance>
     <value>8552</value>
     <text>5.3 mi</text>
   </distance>
 </element>
</row>
</DistanceMatrixResponse>

在VBA中添加對“ Microsoft XML,v3.0”的引用后,可以使用以下內容;

Sub GetSingleNodes()
    Dim objXML As MSXML2.DOMDocument
    Dim strXML As String
    Set objXML = New MSXML2.DOMDocument

    Set htm = CreateObject("htmlFile")
    num1 = Cells(2, 2).Value
    With CreateObject("msxml2.xmlhttp")
        .Open "GET", "https://maps.googleapis.com/maps/api/distancematrix/xml?origins=sy8 2jp&destinations=" & num1 & "&mode=driving&language=en-GB&v=3&sensor=false&units=imperial", False
        .send
        xmlresp = .responseText
    End With

    objXML.LoadXML (xmlresp)
    Dim objElem As MSXML2.IXMLDOMElement
    Status = objXML.SelectSingleNode("DistanceMatrixResponse/row/element/status").Text
    If Status = "OK" Then
        Duration = objXML.SelectSingleNode("DistanceMatrixResponse/row/element/status/duration/text").Text
        Distance = objXML.SelectSingleNode("DistanceMatrixResponse/row/element/status/distance/text").Text
    End If
End Sub

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM