如何通过Excel Web查询提取Google Directions API的距离?

我有一个在Excel中的起源和目的地很长的名单,使用webquery我可以填写城市和邮政编码给一个webquery,如:

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

这给我一个长的XML文件,但我所需要的只是距离。 有没有办法只提取距离值?

或者我应该只是运行一个macros脚本来逐一提取距离? (由于每次我询问服务器时格式都大致相同)

简短的答案是XPath – 如果您要使用任何types的XML,那么非常值得学习

在Excel的macros编辑器中,转至工具>参考,并添加对“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 

要扩展这个覆盖多个行程,您只需循环遍历所需的来源和目的地,将每个对作为parameter passing给此过程,然后以您需要的任何格式输出结果