问题
The purpose of my code is to run a report on a website with specified criteria. I want to search for all of the "distance" criteria, which prompts a message box asking if I'm sure. I want my code to be able to click the "Ok" button. However, my code stops running once the "Submit" button is hit and is hung until the "Ok" button is hit.
Note: I cannot change the HTML or JavaScript
Here's the VBA code
Sub Data_Grab()
'Open Internet Explorer and webpage
Dim IE As Object
Set IE = CreateObject("InternetExplorer.Application")
IE.Visible = True
IE.Navigate "insert website here"
'wait for page to finish loading
Do While IE.Busy
Loop
'get a reference to the search form by finding the id in the web page's object model
Dim daysAs Object
Dim city As Object
Set days= IE.Document.getElementByID("age"): days.Value = "10"
Set city= IE.Document.getElementByID("location"): city.Value = "LA"
'click the search button
With IE.Document
Set elems = .getElementsByTagName("input")
For Each e In elems
If (e.getAttribute("value") = "Submit") Then
e.Click
Exit For
End If
Next e
End With
End Sub
The relevant HTML/JavaScript code from the website source
if (!distanceSelect) {
proceed = confirm("Are you sure you wish to search all " + question + "? Performance issues may occur.");
} else {proceed = true;}
And
<input class="contentarea" type="button" value="Submit" id="submit" onclick="javascript:loadReport();" />
I've tried numerous different solution, such as SendKeys and creating a ShellScript, but I haven't been able to get any of them to work.
Thank you.
回答1:
One way would be to override confirm
with execScript
:
Dim ie As Object, win As Object
Set ie = CreateObject("InternetExplorer.Application")
ie.Visible = True
ie.Navigate "https://stackoverflow.com"
Do While ie.Busy: DoEvents: Loop
Set win = ie.Document.parentWindow
win.execScript "window.confirm = function(){return true;};"
来源:https://stackoverflow.com/questions/46165674/clicking-javascript-confirmation-button-in-vba-script