First off, this is the sort of website I am trying to download files from (via clicking on "Download Data" with the CSV option on). The problematic code (I think; it's hard to tell, partially because it only occurs when running the code at full speed, not stepping through, and partially because the problem is inconsistent, in that it doesn't occur all the time), is this:
Option Explicit 'this stuff at the beginning, of course
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
Sub ContactWeb(ByVal URL As String)
Dim IE As InternetExplorer
'leaving these here so you can see what it is I'm working with right now
Dim Doc As Object, Elmt As Object
Dim HTMLColl As MSHTML.IHTMLElementCollection
Dim Handle As LongPtr
Dim CUI As IUIAutomation
Dim HandleElement As IUIAutomationElement
Dim Condition As IUIAutomationCondition
Dim Button As IUIAutomationElement
Dim InvokePattern As IUIAutomationInvokePattern
Set IE = New InternetExplorer
With IE
'code that loops through elements/clicks on csv and download data goes here
Set CUI = New CUIAutomation
'this point on just clicks "save" on the "do you want to open or save" bar
SetHandle:
Do
Handle = FindWindowEx(.Hwnd, 0, "Frame Notification Bar", vbNullString)
Loop While Handle = 0
If Handle = 0 Then 'just in case it somehow breaks out of that loop
.Visible = True
MsgBox "Could not download file; please do so manually."
Stop
GoTo SetHandle 'I really really *really* hate GoTo
'but I wasn't sure how to eliminate it in this case
End If
'this is the spot I think where it starts failing sometimes
'or at least, the above seems to work a lot more consistently
DoEvents 'if you try to go through this full tilt
'it will return "object variable or with block variable not set"
'so this slows it down a bit
Set HandleElement = CUI.ElementFromHandle(ByVal Handle)
DoEvents
Set Condition = CUI.CreatePropertyCondition(UIA_NamePropertyId, "Save")
DoEvents
Set Button = HandleElement.FindFirst(TreeScope_Subtree, Condition)
'this is the only part that actually requires IE to be visible
'(for reasons unknown to me)
DoEvents
Set InvokePattern = Button.GetCurrentPattern(UIA_InvokePatternId)
DoEvents
InvokePattern.Invoke
.Quit
End With
End Sub
So as mentioned, this code always runs, but the file doesn't always appear...if I run it automatically. When I run it step by step, it always works like a charm (except for that one time it got stuck in an eternal loop - where I have a comment wondering if complete or interactive makes more sense). Can someone help me out here? Why is this happening?