【发布时间】:2019-04-28 21:38:41
【问题描述】:
我有一个计算两点之间距离的宏。我无法让它工作,需要一些帮助来调试它。
我创建了一个 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
【问题讨论】:
-
当你说它不起作用时......它做了什么而不是工作?它是否给出消息、父应用程序是否崩溃、是否发出响亮的哔哔声并从后面喷出烟雾?
-
给出#VALUE!错误(在我写公式GetDT(......)时在excel界面上,而不是在VBA界面上),而不是2点之间的距离值
-
因此,当在 VBA 环境中作为函数运行时,它会返回正确的值,但当作为工作表函数输入时,它就不起作用 - 有很多 limitations when using a UDF。我认为
Set oXH = CreateObject("msxml2.xmlhttp")可能属于这一点,但我不确定。
标签: vba google-api xmlhttprequest