如何通过Excel网页查询从Google Directions API中提取距离?

Mic*_*ael 4 api excel vba distance

我在Excel中有很长的起源和目的地列表,使用webquery我可以填写城市和邮政编码,以提供如下网络查询:

http://maps.googleapis.com/maps/api/directions/xml?origin=Scoresby&destination=Melborne&sensor=false

这给我留下了一个很长的XML文件,但我需要的只是距离.有没有办法只提取距离值?

或者我应该只运行一个宏脚本来逐一提取距离?(由于每次询问服务器时格式大致保持不变)

bar*_*owc 5

简短的回答是XPath - 如果您要使用任何类型的XML,那么值得学习

在Excel的宏编辑器中,转到工具>引用并添加对"Microsoft XML,v6.0"的引用,现在插入>模块并添加以下代码:

Sub getDistances()

Dim xhrRequest As XMLHTTP60
Dim domDoc As DOMDocument60
Dim ixnlDistanceNodes As IXMLDOMNodeList
Dim ixnNode As IXMLDOMNode
Dim lOutputRow As Long

' Read the data from the website
Set xhrRequest = New XMLHTTP60
xhrRequest.Open "GET", "http://maps.googleapis.com/maps/api/directions/xml?origin=Scoresby&destination=Melborne&sensor=false", False
xhrRequest.send

' Copy the results into a format we can manipulate with XPath
Set domDoc = New DOMDocument60
domDoc.loadXML xhrRequest.responseText

' The important bit: select every node called "value" which is the child of a node called "distance" which is
' in turn the child of a node called "step"
Set ixnlDistanceNodes = domDoc.selectNodes("//step/distance/value")

' Basic stuff to output the distances
lOutputRow = 1
With Worksheets("Sheet1")
    .UsedRange.ClearContents
    For Each ixnNode In ixnlDistanceNodes
        .Cells(lOutputRow, 1).Value = ixnNode.Text
        lOutputRow = lOutputRow + 1
    Next ixnNode
End With

Set ixnNode = Nothing
Set ixnlDistanceNodes = Nothing
Set domDoc = Nothing
Set xhrRequest = Nothing

End Sub
Run Code Online (Sandbox Code Playgroud)

要扩展它以覆盖多个行程,您只需遍历所需的原点和目的地,将每一对作为参数传递给此过程,然后以您需要的任何格式输出结果

  • 非常好的例子.就像一个提醒(我不想成为一名funspoiler):使用Google Maps API也需要您显示Google地图("Directions API可能只能与显示结果一起使用谷歌地图",http://code.google.com/intl/en/apis/maps/documentation/directions/#Limits"虽然在这个特定的例子中我看不出如何以有用的方式完成它.只是在说. (2认同)