Vba downloadfile

RFGOES

New Member
Joined
Mar 9, 2017
Messages
15
Hello, I'm trying to download a file, but I can not. The command can click to download, but I can not automatically save it to the folder I'd like. Could anyone help?


Follow the code:





Sub Update()


Dim IE As Object
Set IE = CreateObject("InternetExplorer.Application")
With IE


IE.Visible = True
.navigate "http://bvmf.bmfbovespa.com.br/opcoes/opcoes.aspx?idioma=pt-br"


Do While .Busy: DoEvents: Loop
Do While .readyState <> 4: DoEvents: Loop

'Type the date that is in cell A1 in the webpage
IE.Document.forms.Item(0).Item(12).Value = Format(Sheets("SPLAN").Range("A1"), "dd/mm/yyyy")

'Click fetch date to generate the file to download
IE.Document.forms.Item(0).Item(13).Click


'I need to now download the file automatically into my "c: \ mydocuments" folder
'Save file automatically in folder "c: \ mydocuments"




End With
End Sub
 

Excel Facts

Return population for a City
If you have a list of cities in A2:A100, use Data, Geography. Then =A2.Population and copy down.
Upvote 0
It easier to help if you post the error message and code here. Please post inside CODE tags - the # icon in the message reply editor.

To fix the error, replace the lines in red with:
Code:
#If VBA7 Then
    Private Declare PtrSafe Function FindWindowEx Lib "user32" Alias "FindWindowExA" _
        (ByVal hWnd1 As LongPtr, ByVal hWnd2 As LongPtr, ByVal lpsz1 As String, ByVal lpsz2 As String) As LongPtr
#Else
    Private Declare Function FindWindowEx Lib "user32" Alias "FindWindowExA" _
        (ByVal hWnd1 As Long, ByVal hWnd2 As Long, ByVal lpsz1 As String, ByVal lpsz2 As String) As Long
#End If
What are your Windows OS, Excel and IE versions?
 
Upvote 0
I use windows 7 64 bit, excel is 2007. Would it be possible to use my code in Google Chrome ??




I tried to use the code but nothing happens. Same screen: want to open, save as, cancel ?

Follow code :






Dim ie As InternetExplorer, doc As HTMLDocument, WshtTA As Worksheet, Mes As Variant, UserDldD As String, Marca As String, FileName As String, New_FileName As String
Dim TR As IHTMLElementCollection, aTag As IHTMLElementCollection
Dim AlertsT As IHTMLElement, a As IHTMLElement
Dim d As IHTMLElement, DPath As String
Dim h As Long, o As IUIAutomation, e As IUIAutomationElement, iCnd As IUIAutomationCondition, Button As IUIAutomationElement, InvokePattern As IUIAutomationInvokePattern




#If VBA7 Then
Private Declare PtrSafe Function FindWindowEx Lib "user32" Alias "FindWindowExA" _
(ByVal hWnd1 As LongPtr, ByVal hWnd2 As LongPtr, ByVal lpsz1 As String, ByVal lpsz2 As String) As LongPtr
#Else
Private Declare Function FindWindowEx Lib "user32" Alias "FindWindowExA" _
(ByVal hWnd1 As Long, ByVal hWnd2 As Long, ByVal lpsz1 As String, ByVal lpsz2 As String) As Long
#End If




Sub Download()
Dim ie As Object
Dim strURL As String



strURL = "http://bvmf.bmfbovespa.com.br/opcoes/opcoes.aspx?idioma=pt-br"


Set ie = CreateObject("InternetExplorer.Application")
With ie

.navigate strURL



Do Until .ReadyState = 4: DoEvents: Loop

ie.Visible = True


ie.Document.forms.Item(0).Item(12).Value = Format(Sheets("plan1").Range("A1"), "dd/mm/yyyy")


ie.Document.forms.Item(0).Item(13).Click


Do While .Busy: DoEvents: Loop



Set o = New CUIAutomation

h = ie.hWnd
h = FindWindowEx(h, 0, "Frame Notification Bar", vbNullString)

If h = 0 Then Exit Sub

Set e = o.ElementFromHandle(ByVal h)

Set iCnd = o.CreatePropertyCondition(UIA_NamePropertyId, "Save")


Set Button = e.FindFirst(TreeScope_Subtree, iCnd)


Set InvokePattern = Button.GetCurrentPattern(UIA_InvokePatternId)

InvokePattern.Invoke

Application.Wait (Now() + TimeValue("0:00:05"))


End With
End Sub
 
Upvote 0
I use windows 7 64 bit, excel is 2007. Would it be possible to use my code in Google Chrome ??
No, I don't think VBA can automate Chrome.

I tried to use the code but nothing happens. Same screen: want to open, save as, cancel ?
Which IE version?

If IE8 then the UIAutomation code won't work.
 
Upvote 0
Try this code. It uses IUIAutomation to control the IE Frame Notification Bar (at the bottom of the IE window): click Save, wait for the download to complete, then click the X to close the bar. It seems to work consistently as long as you don't close the bar whilst the download is in progress (IE redisplays it when the download has finished) or click View Downloads on the bar.

Try the code unchanged at first, however you will probably need to edit the code to change the strings which appear on your IE Frame Notification Bar in your language - "Save", "Close" and "download has completed". These lines are marked with the 'Language comment.

You must set the references noted at the top of the code - in Tools -> References in the VBA editor.

Code:
'References required:
'Microsoft Internet Controls (for InternetExplorer class)
'Microsoft HTML Object Library (for HTMLDocument and related classes)
'UIAutomation (for IUIAutomation and related classes)


Option Explicit

'https://msdn.microsoft.com/en-us/library/office/gg264421.aspx
'64-Bit Visual Basic for Applications Overview

#If VBA7 Then
    'New VBA version 7 compiler, therefore >= Office 2010
    'PtrSafe means function works in 32-bit and 64-bit Office
    'LongPtr type alias resolves to Long (32 bits) in 32-bit Office, or LongLong (64 bits) in 64-bit Office
    Private Declare PtrSafe Sub Sleep Lib "kernel32" (ByVal dwMilliseconds As LongPtr)
    Private Declare PtrSafe Function SetForegroundWindow Lib "user32.dll" (ByVal hwnd As LongPtr) As LongPtr
    Private Declare PtrSafe Function FindWindowEx Lib "user32" Alias "FindWindowExA" (ByVal hWnd1 As LongPtr, ByVal hWnd2 As LongPtr, ByVal lpsz1 As String, ByVal lpsz2 As String) As LongPtr
#Else
    'Old VBA version 6 or earlier compiler, therefore <= Office 2007
    Private Declare Sub Sleep Lib "kernel32" (ByVal milliseconds As Long)
    Private Declare Function SetForegroundWindow Lib "user32.dll" (ByVal hwnd As Long) As Long
    Private Declare Function FindWindowEx Lib "user32" Alias "FindWindowExA" (ByVal hWnd1 As Long, ByVal hWnd2 As Long, ByVal lpsz1 As String, ByVal lpsz2 As String) As Long
#End If


Public Sub IE_Download_File()

    Dim IE As InternetExplorer
    Dim HTMLdoc As HTMLDocument
    Dim URL As String
    
    URL = "http://bvmf.bmfbovespa.com.br/opcoes/opcoes.aspx?idioma=pt-br"
    
    Set IE = New InternetExplorer
    With IE
        .Visible = True
        .navigate URL
        SetForegroundWindow .hwnd
        Do While .Busy Or .readyState <> 4: DoEvents: Loop
        Set HTMLdoc = .document
    End With
    
    'Enter download date from Sheet1 cell A2
    '< input name="ctl00$contentPlaceHolderConteudo$posicoesAbertoEmp$txtConsultaDataDownload" id="ctl00_contentPlaceHolderConteudo_posicoesAbertoEmp_txtConsultaDataDownload" readonly="readonly" class="datepicker hasDatepicker" value="10/03/2017" *******="alert('Selecione a data no ícone do calendário ao lado.');" onkeypress="alert('Selecione a data no ícone do calendário ao lado.');" type="text" >
    
    'HTMLdoc.getElementById("ctl00_contentPlaceHolderConteudo_posicoesAbertoEmp_txtConsultaDataDownload").Value = Format(Worksheets("Sheet1").Range("A2").Value, "dd/mm/yyyy")
    HTMLdoc.forms(0).Item(12).Value = Format(Worksheets("Sheet1").Range("A2").Value, "dd/mm/yyyy")
    
    'Click Buscar button
    '< input name="ctl00$contentPlaceHolderConteudo$posicoesAbertoEmp$btnBuscarArquivos" value="buscar" id="ctl00_contentPlaceHolderConteudo_posicoesAbertoEmp_btnBuscarArquivos" class="button expand" type="submit" >
    
    'HTMLdoc.getElementById("ctl00_contentPlaceHolderConteudo_posicoesAbertoEmp_btnBuscarArquivos").Click
    HTMLdoc.forms(0).Item(13).Click

    Download_File IE.hwnd
    Debug.Print Format(Now, "hh:mm:ss"); " Finished"

End Sub


#If VBA7 Then
Private Sub Download_File(IEhwnd As LongPtr)
#Else
Private Sub Download_File(IEhwnd As Long)
#End If

    #If VBA7 Then
        Dim hwnd As LongPtr
    #Else
        Dim hwnd As Long
    #End If
    
    Dim UIAuto As IUIAutomation
    Dim UIAutoElem As IUIAutomationElement, UIAutoElemButton As IUIAutomationElement, UIAutoElemText As IUIAutomationElement
    Dim UIAutoElemToolbar As IUIAutomationElement
    Dim UIAutoCond As IUIAutomationCondition, UIAutoCond1 As IUIAutomationCondition, UIAutoCond2 As IUIAutomationCondition
    Dim UIAutoInvPatt As IUIAutomationInvokePattern
    Dim timeout As Date
    Dim notificationBarText As String, p1 As Long, p2 As Long
    Dim downloadedFileName As String
    
    Const DebugMode As Boolean = False
    
    'Create UIAutomation object
    
    Set UIAuto = New CUIAutomation
        
    'Find the IE11 Frame Notification bar, waiting a maximum of 10 seconds
    
    timeout = DateAdd("s", 10, Now)
    Do
        hwnd = FindWindowEx(IEhwnd, 0, "Frame Notification Bar", vbNullString)
        DoEvents
        Sleep 200
    Loop While hwnd = 0 And Now < timeout
    If DebugMode Then Debug.Print Format(Now, "hh:mm:ss"); " Frame Notification Bar " & hwnd
    
    If hwnd = 0 Then
        MsgBox "IE download Frame Notification bar does not exist"
        Exit Sub
    End If
    
    'Get UIAutomation element
    
    Set UIAutoElem = UIAuto.ElementFromHandle(ByVal hwnd)
    
    'Create conditions to find the "Save" button (split button type)
    'Name      = Save
    'Class     =
    'Ctrl type = 50031
    'Ctrl name = split button
    'Value     =
    
    Set UIAutoCond1 = UIAuto.CreatePropertyCondition(UIA_NamePropertyId, "Save")  'Language
    Set UIAutoCond2 = UIAuto.CreatePropertyCondition(UIA_ControlTypePropertyId, UIA_SplitButtonControlTypeId)
    Set UIAutoCond = UIAuto.CreateAndCondition(UIAutoCond1, UIAutoCond2)
    
    'Find the "Save" button, waiting until it exists
    
    Do
        Set UIAutoElemButton = UIAutoElem.FindFirst(TreeScope_Descendants, UIAutoCond)
        Sleep 200
        If DebugMode Then Debug.Print Format(Now, "hh:mm:ss"); " Find Save"
        DoEvents
    Loop While UIAutoElemButton Is Nothing
        
    'Click the "Save" button, waiting until it doesn't exist
    
    Do
        Set UIAutoInvPatt = UIAutoElemButton.GetCurrentPattern(UIA_InvokePatternId)
        On Error Resume Next  'ignore error if Save is clicked and it doesn't exist
        UIAutoElemButton.SetFocus
        UIAutoInvPatt.Invoke
        On Error GoTo 0
        If DebugMode Then Debug.Print Format(Now, "hh:mm:ss"); " Save clicked"
        Set UIAutoElemButton = UIAutoElem.FindFirst(TreeScope_Descendants, UIAutoCond)
        Sleep 200
    Loop Until UIAutoElemButton Is Nothing
    
    'Create conditions to find "Notification bar Text"
    'Name      = Notification bar Text
    'Class     =
    'Ctrl type = 50020
    'Ctrl name = Text
    'Value     = The xxxxxxx.yyy download has completed.
    
    Set UIAutoCond1 = UIAuto.CreatePropertyCondition(UIA_NamePropertyId, "Notification bar Text")  'Language?
    Set UIAutoCond2 = UIAuto.CreatePropertyCondition(UIA_ControlTypePropertyId, UIA_TextControlTypeId)
    Set UIAutoCond = UIAuto.CreateAndCondition(UIAutoCond1, UIAutoCond2)
    
    'Find the "Notification bar Text" and wait until its Value contains "download has completed"
    
    Do
        Set UIAutoElemText = UIAutoElem.FindFirst(TreeScope_Descendants, UIAutoCond)
        Sleep 200
        DoEvents
        notificationBarText = ""
        If Not UIAutoElemText Is Nothing Then
            notificationBarText = UIAutoElemText.GetCurrentPropertyValue(UIA_LegacyIAccessibleValuePropertyId)
        End If
        If DebugMode Then Debug.Print Format(Now, "hh:mm:ss"); " "; notificationBarText
    Loop Until InStr(notificationBarText, "download has completed")
    
    'Create conditions to find the "Close" button
    
    Set UIAutoCond1 = UIAuto.CreatePropertyCondition(UIA_NamePropertyId, "Close")  'Language
    Set UIAutoCond2 = UIAuto.CreatePropertyCondition(UIA_ControlTypePropertyId, UIA_ButtonControlTypeId)
    Set UIAutoCond = UIAuto.CreateAndCondition(UIAutoCond1, UIAutoCond2)
        
    'Find the "Close" button, waiting until it exists
    
    Do
        Set UIAutoElemButton = UIAutoElem.FindFirst(TreeScope_Descendants, UIAutoCond)
        Sleep 200
        If DebugMode Then Debug.Print Format(Now, "hh:mm:ss"); " Find Close"
        DoEvents
    Loop While UIAutoElemButton Is Nothing
    
    'Click the "Close" button
    
    UIAutoElemButton.SetFocus
    Set UIAutoInvPatt = UIAutoElemButton.GetCurrentPattern(UIA_InvokePatternId)
    UIAutoInvPatt.Invoke
    If DebugMode Then Debug.Print Format(Now, "hh:mm:ss"); " Close clicked"
        
    Set UIAutoInvPatt = Nothing
    Set UIAutoElemButton = Nothing
    Set UIAuto = Nothing
    
    'Extract file name from notification bar text, e.g. "The xxxxxxx.yyy download has completed."
    
    p1 = InStr(notificationBarText, "The ") + 4
    p2 = InStr(p1, notificationBarText, " download has completed")  'Language
    
    downloadedFileName = Mid(notificationBarText, p1, p2 - p1)
    Debug.Print Format(Now, "hh:mm:ss"); " Downloaded " & downloadedFileName

End Sub
 
Upvote 0
Hi John, it's working, the problem is that the IE window only closes if I push the button. And when I close it gives me the following message:


Error in execution time '-2147467259 (80004005)':


Automation error
Unspecified error


I wish I could use the as False. IE.Visible = FALSE. If I put: False, the code hangs.


If it gets too much work for you, I use the same simple code, no problem. I do not want to waste your time. Thanks for the help.
 
Upvote 0
Hi John, it's working, the problem is that the IE window only closes if I push the button.
The code doesn't close the main IE window. It closes the download notification bar at the bottom of the IE window. If the download notification bar is not being closed then it could be because the name of the X close icon is not "Close", but "Cerca" in your IE language. Therefore change this line:

Code:
    Set UIAutoCond1 = UIAuto.CreatePropertyCondition(UIA_NamePropertyId, "Cerca")  'was "Close"

I tried IE.Visible = False and the code kept looping looking for the "Save" button. Therefore it looks like IE must be visible for the UIAutomation code to work.

There is another approach which doesn't use IE; instead VBA can send http requests to download the file. I will see if this method works on your webpage.
 
Upvote 0

Forum statistics

Threads
1,223,999
Messages
6,175,887
Members
452,679
Latest member
darryl47nopra

We've detected that you are using an adblocker.

We have a great community of people providing Excel help here, but the hosting costs are enormous. You can help keep this site running by allowing ads on MrExcel.com.
Allow Ads at MrExcel

Which adblocker are you using?

Disable AdBlock

Follow these easy steps to disable AdBlock

1)Click on the icon in the browser’s toolbar.
2)Click on the icon in the browser’s toolbar.
2)Click on the "Pause on this site" option.
Go back

Disable AdBlock Plus

Follow these easy steps to disable AdBlock Plus

1)Click on the icon in the browser’s toolbar.
2)Click on the toggle to disable it for "mrexcel.com".
Go back

Disable uBlock Origin

Follow these easy steps to disable uBlock Origin

1)Click on the icon in the browser’s toolbar.
2)Click on the "Power" button.
3)Click on the "Refresh" button.
Go back

Disable uBlock

Follow these easy steps to disable uBlock

1)Click on the icon in the browser’s toolbar.
2)Click on the "Power" button.
3)Click on the "Refresh" button.
Go back
Back
Top