如何使用appIE.Document.Body.innerHTML

所以我试图检索给定的邮政编码的经度和纬度,并试图使用VBA将其放置到Excel工作表。 我的代码如下:

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
并parsing我想要的数据的值。 但是,代码点击appIE.Navigate sLocationData的那一刻,
系统会提示保存名为“geo”的文件。 当保存并打开一个.txt文件,我得到完全相同的JSON格式的值,但我需要在我的工作表本身的值。

有没有办法做到这一点?

提前致谢!

这个链接在Firefox中不起作用 – 响应610.如果我删除空格和下划线,它的工作原理。 我不知道为什么IE要下载,可能是一些设置,告诉它总是下载JSON而不是渲染它。 在任何情况下,考虑使用MSXML的http请求,而不是自动化IE。

设置对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