使用VBA方法通过Bing API获取距离不起作用

问题描述

当我使用#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

解决方法

三件事。

  1. 您需要将小写字母与州和州之间的2个字母缩写传递给对方

  2. 上面的内容需要使用Urlencoded

  3. 响应具有您需要添加的默认名称空间。对于后者,我求助于使用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