4

住所データベースをジオコーディングできる VBA スクリプトを作成しようとしています。私はこのスクリプトに数日間取り組んできましたが、専門家にアドバイスを求めなければならない時が来ると思います。そのため、スクリプトで Google マップの URL にアクセスし、緯度と経度の値を検索する必要があります。その情報をローカルの XML ドキュメントから抽出することはできましたが、Google マップ サーバーから読み取った 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

そして、上記のコードは何も返さず、エラーさえも返しません。このコードを修正する方法を教えてください。前もって感謝します。

PS 私は VBA の初心者ですが、この問題についてよく調べました。

4

1 に答える 1

4

これを試して:

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」を使用しました。最初に見つかった緯度の値に問題がない場合は、次のオプションのいずれかを使用できます。

 odc.SelectSingleNode("GeocodeResponse/result/geometry/location/lat")
 odc.SelectSingleNode("//lat")

Xpath について読めば読むほど、作業が簡単になります。VBA は Xpath 1.0 でのみ機能することに注意してください (Xpath 2 はサポートされていません)。

于 2012-11-05T13:48:05.857 に答える