首先,感謝您花時間和興趣來解決這個問題。我一直在使用VBA在Excel中自動執行手動任務,但最近纔開始探索使用VBA訪問Web。使用VBA處理IE中的打開/保存/取消對話框窗口
目標:從網站無法在網頁源代碼中找到文件url的網站自動下載文件(每天約15-20個xlsx文件)。
下面是手動下載這些步驟時我經常採用的步驟。
- 打開登錄頁面,並輸入登錄憑據,以訪問感興趣的網頁(即一個對所有報告)
- 在登錄後,導航與報告 注1的網頁:它是設置,使1網頁(唯一的URL)=顯示器頂部55的結果的第一頁
注2:在同一個頁面也有一個按鈕導出/保存不同格式的整個報表
下載報告
導航到下一個網頁(在同一網站內),並重復步驟2和3(有15-20報告/網頁瀏覽)
據我已經得到了因爲通過使用SendKeys單擊保存來下載第一個報告。雖然有時會在對話窗口出現時立即停止,但這已經達到了最遠的地步。之後,我無法導航到另一個網頁,並重復相同的步驟下載。我的直覺是,單擊保存按鈕後出現的打開/打開文件/查看下載對話窗口不允許我重複下載/保存過程...
我試着看源代碼網站查看是否可以找到該文件的網址,但找不到它(不知道是否必須這樣做,導出只發生在點擊隱藏文件url的提交按鈕或其他類似運行腳本之後) 。我對WinHttpRequest不是很熟悉,但似乎是進行我的谷歌研究之後的首選方法。它也看起來像這將需要有一個文件的URL,但不知道在這...
下面是我到目前爲止的代碼。任何幫助將非常非常感激。謝謝! :)
Sub webMacro()
Dim IE As New InternetExplorer
IE.Visible = True 'change False --> True to open the IE window
IE.navigate "https://websiteURL.net//apps/login.aspx"
Do
DoEvents
Loop Until IE.readyState = READYSTATE_COMPLETE
Dim Doc As HTMLDocument: Set Doc = IE.document
Doc.getElementById("username").Value = "myusername" 'login to the website
Doc.getElementById("pass").Value = "mypassword"
Doc.getElementById("Enter").Click
Sleep (1000)
Do
DoEvents
Loop Until IE.readyState = READYSTATE_COMPLETE
IE.navigate "https://firstReportWebPage.net//apps/....." 'navigates to the first webpage (report) to download after login
Do
DoEvents
Loop Until IE.readyState = READYSTATE_COMPLETE
Doc.getElementById("##########").Click 'ID of the Export/Save button
Do
DoEvents
Loop Until IE.readyState = READYSTATE_COMPLETE
Doc.getElementById("###########").Click 'ID of the Submit button
Do
DoEvents
Loop Until IE.readyState = READYSTATE_COMPLETE
Doc.getElementById("############").Click 'ID of the field right before it enters the Open/Save/Cancel dialogue window
Do
DoEvents
Loop Until IE.readyState = READYSTATE_COMPLETE
Application.Wait (Now + TimeValue("0:00:02")) 'here I'm using the SendKeys to mimic what I would manually do on the keyboard to get to the "Save" button
SendKeys "{TAB}", True
SendKeys "{TAB}", True
SendKeys "{DOWN}", True
SendKeys "{ENTER}", True
Sleep (1000)
Do
DoEvents
Loop Until IE.readyState = READYSTATE_COMPLETE
Sleep (1000)
''***This is where it almost always gets stuck...here I'm attempting to get to the Open/Open file/View downloads dialogue window by clicking on the field right before entering the dialogue window using the tab key; same as above when trying to click on the "Save" button in the Open/Save/Cancel dialogue window.
Doc.getElementById("############").Click 'ID of the field right before it enters the Open/Open File/View Downloads dialogue window
Sleep (1000)
Do
DoEvents
Loop Until IE.readyState = READYSTATE_COMPLETE
Sleep (1000)
Application.Wait (Now + TimeValue("0:00:02"))
Sleep (1000)
SendKeys "{TAB}", True
Sleep (1000)
SendKeys "{TAB}", True
Sleep (1000)
SendKeys "{TAB}", True
Sleep (1000)
SendKeys "{TAB}", True
Sleep (1000)
SendKeys "{ENTER}", True
Sleep (1000)
'some other code to go here...
End Sub