Reputation: 31237
I'm working on an internet explorer automation project. The code downloads and saves a file from a website. Its possible to download and save file using 'SendKeys' but its not a reliable method as I cannot detect the download notification:
Is there a way to download and save the file without 'SendKeys'? or at least is there a way to detect the presence of this notification?
Ps - I have referred to these links, which are helpful for IE8 downloads:
Any help?
Upvotes: 2
Views: 1598
Reputation: 8591
Why to use SendKeys
method to download a file? Sorry, this is wrong approach.
Use API!
Solution 1:
Private Declare Function URLDownloadToFile Lib "urlmon" Alias _
"URLDownloadToFileA" (ByVal pCaller As Long, ByVal szURL As String, ByVal _
szFileName As String, ByVal dwReserved As Long, ByVal lpfnCB As Long) As Long
Sub DownloadFilefromWeb()
Dim strSavePath As String
Dim URL As String, ext As String
Dim buf, ret As Long
URL = Worksheets("References & Resources").Range("URLMSL").Value
buf = Split(URL, ".")
ext = buf(UBound(buf))
strSavePath = ThisWorkbook.Path & "\" & "DownloadedFile." & ext
ret = URLDownloadToFile(0, URL, strSavePath, 0, 0)
If ret = 0 Then
MsgBox "Download has been succeed!"
Else
MsgBox "Error"
End If
End Sub
Source: VBA - Save a file from a Website
Solution 2:
Option Explicit
Sub DownloadXLFileFromURL()
Dim myURL As String, sFilename As String
myURL = "http://img.chandoo.org/hw/max-change-problem.xlsx"
sFilename = Environ("SystemDrive") & Environ("HomePath") & _
Application.PathSeparator & "Desktop" & Application.PathSeparator & _
"file.xlsx"
Dim WinHttpReq As Object, oStream As Object
Set WinHttpReq = CreateObject("Microsoft.XMLHTTP")
WinHttpReq.Open "GET", myURL, False ', "username", "password"
WinHttpReq.Send
myURL = WinHttpReq.ResponseBody
If WinHttpReq.Status = 200 Then
Set oStream = CreateObject("ADODB.Stream")
oStream.Open
oStream.Type = 1
oStream.Write WinHttpReq.ResponseBody
oStream.SaveToFile sFilename, 2 ' 1 = no overwrite, 2 = overwrite
oStream.Close
End If
End Sub
Source: Download file from URL using VBA
Solution 3:
Finally, you can create custom class, which can create an instance of MS IE. Now, you are able to control/manage of IE object via using its properties and events, such as DownloadBegin, DownloadComplete, FileDownload
Please, see: Using the WebBrowser Control from Visual Basic
Note: Never before i tried it...
Upvotes: 1