使用 VBA 方法通过 Bing API 获取距离
Posted
技术标签:
【中文标题】使用 VBA 方法通过 Bing API 获取距离【英文标题】:Get distance via Bing API using VBA method 【发布时间】:2021-01-17 22:38:05 【问题描述】:我正在尝试通过 VBA 创建一个方法,当我使用此方法时,它会显示 #NAME?有时是#value。
Public Function DISTANCE(start As String, dest As String, key As String)
Dim firstVal As String, secondVal As String, lastVal As String
firstVal = "http://dev.virtualearth.net/REST/V1/Routes/Driving?wp.0="
secondVal = "&wp.1=destinations="
lastVal = "&optimize=time&routePathOutput=Points&distanceUnit=km&output=xml&key=" & key
Set objHTTP = CreateObject("MSXML2.ServerXMLHTTP")
URL = firstVal & start & secondVal & dest & lastVal
objHTTP.Open "GET", URL, False
objHTTP.SetRequestHeader "User-Agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.0)"
objHTTP.Send ("")
DISTANCE = Round(Round(WorksheetFunction.FilterXML(objHTTP.ResponseText, "//TravelDistance"), 3) * 1.609, 0)
End Function
【问题讨论】:
你能发布一个输入示例来测试代码吗? DISTANCE("New York", "Miami", "API_KEY") 【参考方案1】:三件事。
您需要以小写字母和 2 个字母缩写表示状态
以上需要urlencoded
响应有一个你需要添加的默认命名空间。对于后者,我求助于使用 MSXML2.DOMDocument 以便能够添加命名空间。
Public Sub test()
Debug.Print GetDistance("new york,ny", "miami,fl", "key")
End Sub
Public Function GetDistance(ByVal start As String, ByVal dest As String, ByVal key As String) As Long
Dim firstVal As String, secondVal As String, lastVal As String, objHTTP As Object, url As String
firstVal = "http://dev.virtualearth.net/REST/V1/Routes/Driving?wp.0="
secondVal = "&wp.1=destinations="
lastVal = "&optmz=time&routePathOutput=Points&distanceUnit=km&output=xml&key=" & key
Set objHTTP = CreateObject("MSXML2.ServerXMLHTTP")
url = firstVal & Application.EncodeURL(LCase$(start)) & secondVal & Application.EncodeURL(LCase$(dest)) & lastVal
objHTTP.Open "GET", url, False
objHTTP.setRequestHeader "User-Agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.0)"
objHTTP.send
Dim xmlDoc As MSXML2.DOMDocument60 'reference to Microsoft XML via VBE>Tools>References
Set xmlDoc = New MSXML2.DOMDocument60
xmlDoc.LoadXML objHTTP.responseText
xmlDoc.SetProperty "SelectionNamespaces", "xmlns:r='http://schemas.microsoft.com/search/local/ws/rest/v1'"
GetDistance = Round(Round(xmlDoc.SelectSingleNode("//r:TravelDistance").Text, 3) * 1.609, 0)
End Function
【讨论】:
以上是关于使用 VBA 方法通过 Bing API 获取距离的主要内容,如果未能解决你的问题,请参考以下文章
使用 Bing 或 Google Maps API 获取用户的位置(纬度、经度)
获取bing图片并自动设置为电脑桌面背景(使用 URLDownloadToFile API函数)
使用 bing map api 获取地址(邮政编码)自动地理定位?