在VBA中从Javascript获取XmlHttpRequest的ReadyState

我有一个Excel文件,可以保存在我的工作周围。

我们必须login到一个网站,以检查某些事情。 用VBA,我得到一个IE窗口打开,我得到它login到网站,并填写一个表格(并提交!)。

但是,我的问题出现,因为表单是使用JavaScript和AJAX提交的。 所以,我不能得到响应数据(这是我开始这整个努力)。

我的问题是这样的:有没有什么办法可以在VBA中循环,直到Javascript XML对象获取数据,还是我完全疯狂尝试?

编辑:由于一个请求,我把我目前的代码。 由于我们的隐私协议,我不能发布说[删除]的项目。 我知道一个事实,一旦响应数据加载它被附加到一个具有“resultsTable”ID的div。但是,我试图循环,直到find该DOM元素不起作用。

编辑#2我终于有了一些工作。 我原来的代码出了什么问题,我不知道ohtml.getElementById()函数是如何工作的,以及如果它什么都没发现,它会返回什么结果。 以下内容等待数据集出现。 然后,它会对数据执行某些操作(不幸的是我无法发布)。 感谢大家!

Private Sub IE_Autiomation() Dim i As Long, r As Range Dim IE As InternetExplorer, ohtml As HTMLDocument Dim ouser As HTMLInputElement, opass As HTMLInputElement, otext As HTMLTextAreaElement, otable As HTMLTable ' Create InternetExplorer Object Set r = Application.Union(ActiveSheet.ListObjects(1).Range, ActiveSheet.ListObjects(2).Range, ActiveSheet.ListObjects(3).Range, ActiveSheet.ListObjects(4).Range) Debug.Print r.Address Set r = Application.Intersect(r, ActiveSheet.Range("B:B,E:E,H:H")) 'Just Trust Me, Ok? Set IE = New InternetExplorer ' Send the form data To URL As POST binary request IE.Navigate "[Removed]" Do While IE.Busy Application.Wait DateAdd("s", 1, Now) Loop Set ohtml = IE.document Set ouser = ohtml.getElementById("USER") Set opass = ohtml.getElementById("PASSWORD") ouser.Value = "[removed]" pw = InputBox("Password?") opass.Value = pw IE.Visible = True ouser.form.submit Do While IE.Busy Application.Wait DateAdd("s", 1, Now) Loop Set otext = ohtml.getElementsByName("vin").Item(0) For Each e In r If e.Offset(0, -1).Value = "" And Not e.Value = "" Then otext.Value = otext.Value & e.Value & ", " End If Next Debug.Print otext.Value otext.Value = Left(otext.Value, Len(otext.Value) - 2) Debug.Print otext.Value Debug.Print "So far, wafles." For Each j In ohtml.getElementsByTagName("input") If j.Value = "Submit" Then Set ouser = j Exit For End If Next ouser.Click 'Here is where I need to wait for the response to load into the HTML ' Wait while IE loading... ' Clean up Set otable = ohtml.getElementById("resultsTable") Do While otable Is Nothing Application.Wait DateAdd("s", 1, Now) Set otable = ohtml.getElementById("resultsTable") Loop 'IE.Quit Set IE = Nothing Set objElement = Nothing Set ohtml = Nothing Set objCollection = Nothing Application.StatusBar = "" End Sub 

使用一个现成的等待循环。

您将需要WinAPI睡眠function:

 Public Declare Sub Sleep Lib "kernel32" (ByVal dwMilliseconds As Long) 'For use in timer function 

然后,在你的请求发送后,你需要做一些类似的事情(例如IE对象,如果你更新你的Q代码,我可以根据你的需要修改)。

 Set IE = CreateObject("InternetExplorer.Application") IE.Navigate "http://google.com" Do While Not IE.readyState = 4 Sleep 250 Loop 

这是做什么睡觉四分之一秒,循环直到文件已经加载。