如何调试计算两点之间距离的宏?

时间:2018-11-27 07:31:07

标签: vba google-api xmlhttprequest

我有一个宏,可以计算两个点之间的距离。我无法使其正常工作,并希望在调试时有所帮助。

我已经创建了Google API密钥,并且也将其合并到其中,但是由于某种原因,宏无法正常工作

Public Function

GetDT(origin_city As String, _
origin_state As String, origin_country As String, _
destination_city As String, _
destination_state As String, destination_country As String _
)

Dim surl                As String
Dim oXH                 As Object
Dim bodytxt             As String

Dim distanc_e           As String


surl = "http://maps.googleapis.com/maps/api/distancematrix/xml?origins=" 
& _
Replace(origin_city, " ", "+") & "+" & Replace(origin_state, " ", "+") & 
"+" & Replace(origin_country, " ", "+") & _
"&destinations=" & _
Replace(destination_city, " ", "+") & "+" & Replace(destination_state, " 
", "+") & "+" & Replace(destination_country, " ", "+") & _
"&mode=driving&units=metric&key=MY_KEY"


Set oXH = CreateObject("msxml2.xmlhttp")

With oXH
    .Open "get", surl, False
    .send
    bodytxt = .responseText
End With

bodytxt = Right(bodytxt, Len(bodytxt) - InStr(1, bodytxt, "<text>") - 5)
tim_e = Left(bodytxt, InStr(1, bodytxt, "</text>") - 1)


bodytxt = Right(bodytxt, Len(bodytxt) - InStr(1, bodytxt, "<text>") - 5)
distanc_e = Left(bodytxt, InStr(1, bodytxt, "</text>") - 1)

GetDT = distanc_e

Set oXH = Nothing

End Function

1 个答案:

答案 0 :(得分:1)

无法使用所提供的信息来自信地回答这个问题。编写一个单独的函数来创建url将使您的代码更具可测试性。使用Option Explicit强制声明所有变量将检测到任何错字。

如果MY_KEY是变量,则网址应类似于"..metric&key=" & MY_KEY

surl = GetDTURL(origin_city, origin_state, origin_country, destination_city, destination_state, destination_country)
Function GetDTURL(origin_city As String, origin_state As String, origin_country As String, destination_city As String, destination_state As String, destination_country As String)
    Dim surl As String
    Const BaseURl As String = "http://maps.googleapis.com/maps/api/distancematrix/xml?origins=@origin_city+@origin_state+@origin_country&destinations=@destination_city+@destination_state+@destination_country&mode=driving&units=metric&key=MY_KEY"
    surl = BaseURl
    surl = Replace(surl, "@origin_city", origin_city)
    surl = Replace(surl, "@origin_state", origin_state)
    surl = Replace(surl, "@origin_country", origin_country)
    surl = Replace(surl, "@destination_city", destination_city)
    surl = Replace(surl, "@destination_state", destination_state)
    surl = Replace(surl, "@destination_country", destination_country)
    surl = Replace(surl, " ", "+")
    GetDTURL = surl
End Function