2012-03-17 11 views
3

私は特定の郵便番号の緯度と経度を取得しようとしています。これをVBAを使用してExcelワークシートに配置しようとしています。次のように私のコードは次のとおりです。appIE.Document.Body.innerHTMLの使い方

Private appIE As Object 

Function GeoCode(sLocationData As String) As String 
'//Dont want to open and close all day long - make once use many 
If appIE Is Nothing Then 
    CreateIEApp 
    '// Creates a new IE App 
    '// if = nothing now then there was an error 
    If appIE Is Nothing Then 
     GeoCode = "Sorry could not launch IE" 
     Exit Function 
    Else 
     '// do nothing 
    End If 
Else 
    '// do nothing 
End If 
'//clearing up input data 
'sLocationData = Replace(sLocationData, ",", " ") 
sLocationData = Replace(sLocationData, " ", "+") 
sLocationData = Trim(sLocationData) 

'//Build URL for Query 
sLocationData = "http://maps.google.com/maps/geo?q=%20_" & sLocationData 

'// go to the google web service and get the raw CSV data 
'// CAUSES PROBLEM AS SPECIFIED BELOW 
appIE.Navigate sLocationData 

Do While appIE.Busy 
    Application.StatusBar = "Contacting Google Maps API..." 
Loop 

Application.StatusBar = False 
On Error Resume Next 

'// Parsing 
GeoCode = appIE.Document.Body.innerHTML 
GeoCode = Mid(GeoCode, InStr(GeoCode, ",") + 1, InStr(GeoCode, "/") - InStr(GeoCode, ",") - 2) 

appIE = Nothing 
End Function 

Google MapsのAPI、このリンクあたりとして、JSON形式の値を返します。

http://maps.google.com/maps/geo?q=%20_400012

私はその後、
appIE.Document.Body.innerHTMLを使用してこの値を取得しようとすると、
と私が欲しいデータのその値を解析する。しかし、コードがappIE.Navigate sLocationDataに達する瞬間、
"geo"というファイルを保存するように求められます。保存して.txtファイルとして開くと、同じJSON形式の値が取得されますが、ワークシート自体の値が必要です。

これを行う方法はありますか?

ありがとうございます!

答えて

2

Firefoxでこのリンクが動作しませんでした - レスポンス610。スペースとアンダースコアを削除すると動作します。私はなぜIEがダウンロードしたいのかわからないでしょう。おそらくJSONをレンダリングするのではなく、ダウンロードするように指示する設定でしょう。いずれにしても、IEを自動化するのではなく、MSXMLのhttp要求を使用することを検討してください。

Microsoft XML、v6.0など(VBE - ツール - 参照)への参照を設定します。

Function GeoCode(sLocData As String) As String 

    Dim xHttp As MSXML2.XMLHTTP 
    Dim sResponse As String 
    Dim lStart As Long, lEnd As Long 

    Const sURL As String = "http://maps.google.com/maps/geo?q=" 
    Const sCOOR As String = "coordinates"": " 'substring that we'll look for later 

    'send the http request 
    Set xHttp = New MSXML2.XMLHTTP 
    xHttp.Open "GET", sURL & sLocData 
    xHttp.send 

    'wait until it's done 
    Do 
     DoEvents 
    Loop Until xHttp.readyState = 4 

    'get the returned data 
    sResponse = xHttp.responseText 

    'find the starting and ending points of the substring 
    lStart = InStr(1, sResponse, sCOOR) 
    lEnd = InStr(lStart, sResponse, "]") 

    GeoCode = Mid$(sResponse, lStart + Len(sCOOR), lEnd - lStart - Len(sCOOR) + 1) 

End Function 

Sub Test() 

    Dim sTest As String 

    sTest = GeoCode("400012") 

    Debug.Assert sTest = "[ 103.9041520, 1.3222160, 0 ]" 

End Sub 
+0

+1 xmlhttpより優れた自動化ie – brettdj