我正在尝试创建一个 VBA 脚本,它可以让我对我的地址数据库进行地理编码。几天来我一直在研究这个脚本,我想有时我不得不向专家请教一些建议。 所以,我希望脚本访问谷歌地图 url 并查找纬度和经度值。我设法从本地 XML 文档中提取了该信息,但我无法使用从谷歌地图服务器读取的 XML 来这样做。对我有用的代码如下:
Sub XMLread()
Dim odc As DOMDocument
Dim nde As IXMLDOMNode
Dim lat As IXMLDOMElement
Dim url As String
Set odc = New MSXML2.DOMDocument
url = "C:\~path~\address.xml"
odc.Load (url)
For Each nde In odc.SelectNodes("GeocodeResponse/result/geometry/location")
Set lat = nde.SelectSingleNode("lat")
Debug.Print lat.Text
Next
End Sub
此代码的作用是打开一个 xml 文件,找到“lat”的值并将其打印在调试窗口中。我打算将结果放在电子表格中,但这不会成为问题。问题在于直接从服务器提取数据。我使用以下代码:
Sub XMLerverRead()
Dim odc As DOMDocument
Dim nde As IXMLDOMNode
Dim lat As IXMLDOMElement
Dim url As String
url="https://maps.googleapis.com/maps/api/geocode/xml?address=1+Infinite+Loop,+Cupertino,+Santa+Clara,+California+95014&sensor=false"
Set odc = New MSXML2.DOMDocument
odc.async = False
odc.Load (url)
For Each nde In odc.SelectNodes("GeocodeResponse/result/geometry/location")
Set lat = nde.SelectSingleNode("lat")
Debug.Print lat.Text
Next
End Sub
而且上面的代码没有返回任何东西,甚至没有错误。你能帮帮我,告诉我如何修复这段代码吗?提前谢谢你。
附言我是 VBA 新手,但我对这个问题做了很好的研究。
最佳答案
试试这个:
Sub XMLerverRead()
Dim odc As DOMDocument
Dim url As String
Dim lat As String
url="https://maps.googleapis.com/maps/api/geocode/xml?address=1+Infinite+Loop,+Cupertino,+Santa+Clara,+California+95014&sensor=false"
Set odc = New MSXML2.DOMDocument
odc.async = False
odc.Load (url)
If odc Is Nothing Then
MsgBox "Odc is not loaded with the Xml."
Else
lat= vbNullString 'This is to assure that the variable lat has no value.'
On Error Resume Next 'We dont want to show the user a system msgbox if the node does not exist'
lat = odc.SelectSingleNode("GeocodeResponse/result/geometry[location_type='ROOFTOP']/location/lat").Text
On Error Goto 0
If lat=vbNullString Then 'Here you can show the user some useful info or do something with your code instead'
MsgBox "There is no Latitude value for a 'ROOFTOP' node in the given XML"
End If
End If
End Sub
编辑:
我对代码做了一些修改以帮助回答您的问题。
注意: 为了示例,我使用了节点“ROOFTOP”。如果您对找到的第一个 lat 值没有问题,则可以使用以下任何选项。
odc.SelectSingleNode("GeocodeResponse/result/geometry/location/lat")
odc.SelectSingleNode("//lat")
您对 Xpath 的了解越多,您的任务就越容易。重要的是要注意 VBA 仅适用于 Xpath 1.0(不支持 Xpath 2)。
关于xml - 使用 VBA 自动地理编码,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13232613/