I'm trying to read out something from a website using an excel vba macro.
(MS Office 365/Windows 10/IE Explorer 11)
I navigate to the webpage. This page is a form where I have to confirm a checkbox and press a button. This works all fine, but how can I read out the webpage after the form has been sended? My code:
Dim objbrowser As New InternetExplorer
objbrowser.Navigate ("http://www.formdemo.htm")
GoSub SubWaitForIE 'I put the wait for IE loop into a sub
set docFile = objbrowser.Document
vCheckbox = docFile.getElementsByName("agreecheck"): vCheckbox.Click
docFile.getElementById("sendbutton").Click
GoSub SubWaitForIE
At this point, the form is transmitted, the result page is loaded.
But how do I get the resultpage in to an object like in
set docFile = objbrowser.Document
again??
Related
I am very new to Selenium and I'm trying to create an application, which gets some information from an excel sheet, logs into a specific facebook page (not a person's profile), and creates a post which contains an image.
So far I've managed to log into the page account but I have no clue on how to upload a certain image due to the fact that it seems that the webdriver cannot interact with the filedialog that appears if I (programmatically) click on the "upload image" button. Also I cannot find any "upload" id or whatsoever.
Posting here the code I need help with:
' After having logged in, this creates a post
Dim ele As WebElement
Dim drv As New WebDriver
Set ele = drv.FindElementByXPath("//*[#aria-label='Crea un post']") ' This selects the "create a new post" button
ele.Click
Application.Wait (100)
If Not IsEmpty(Cells(24, 2)) Then ' Adds picture if there is one specified in the excel sheet
Set ele = drv.FindElementByXPath("//*[#aria-label='Foto/video']") ' This clicks the "add Picture" button, but then the FileDialog appears and I cannot interact with it
ele.Click
ele.SendKeys "C:\mytestimage.png"
End If
Set ele = drv.FindElementByXPath("//*[#aria-label='Scrivi qualcosa a mypage']") ' Italian for "write something to mypage"
ele.SendKeys "Whatever I want to be written in the post"
I'm hoping someone can help. I'm trying to speed up the process of filling a webform that must be completed dozens or hundreds of times with information stored in excel.
To do this, I need one button to open an IE window and navigate to a certain website's login page (I've figured this bit out). The user can then log in and navigate to the form that needs to be filled. Then, I'd like the user to be able to return to the excel page, click another button, which will automatically fill several drop downs and text boxes.
Within Excel, I already have some code to allow the user to search for the particular set of information that needs to go to the form, so all they should have to do is click the button to transfer it over. The first bit of the code is just this:
Public IE As Object
Public Sub OpenIE()
Set IE = CreateObject("InternetExplorer.Application")
IE.Visible = True
IE.Navigate "loginpage url"
End Sub
Where I'm having trouble, however, is having a different function access the same IE window once the user has logged in and navigated to the form. Right now I've got this:
Sub FillMacro()
Dim sh As Object, oWin As Object
Set sh = CreateObject("Shell.Application")
For Each oWin In sh.Windows
If TypeName(oWin.document) = "HTMLDocument" Then
Set IE = oWin
Exit For
End If
Next
IE.Visible = True
Application.Wait (Now + TimeValue("00:00:01"))
IE.document.getElementById("idec").Value = "John"
Application.Wait (Now + TimeValue("00:00:01"))
IE.document.getElementById("idee").Value = "Smith"
End Sub
Most of that I've gotten from other posts on this forum, and while I'm a bit of a novice at this, the problem seems to be that for some reason VBA can't find the text boxes with the id of LastName or FirstName. What's more, the IE.Visible = True doesn't bring the IE window back to the foreground, so I'm trying to find the proper line to do that. When I try to run the code, I get an "Object Required" error at:
IE.document.getElementById("idec").Value = "John"
I've tried searching this site and will continue to look, but any help in the meantime would be greatly appreciated!
On the Internet Explorer page, here is the line for the first text box I'm trying to fill:
<input name="componentListPanel:componentListView:1:component:patientLastNameContainer:patientLastName" class="input300" id="idec" type="text" maxlength="60" value="">
Why not automate logging process as well? Login could be stored in Excel and its value read by macro from cell.
As Tim Williams suggests, if there is Iframe on website, use (for me it works only with contentwindow included):
IE.document.getElementById("iFrameIdHere").contentwindow.document.getElementById("idec").Value = "John"
Instead of Application.Wait use:
Do Until IE.ReadyState = 4 And IE.Busy = False
DoEvents
Loop
It will save you a lot of time when page loads fast and prevent errors when loading exceeds wait time. Use it ONLY after page reloads (meaning after navigating or anything what causes page reloads, especially .click on HTML elements.
Use early binding, it's a bit faster than creating objects. It can increase performance by a few percent based on page loading speed, the faster pages load, the bigger increase.
Set IE = New InternetExplorer
Finally, you can toggle loading pictures, depending on whether you need to download images from website.
Public Sub ShowPictures(ByVal EnabledStatus As Boolean)
Public ScrapingCancelled as Boolean
Dim obj_Shell
Dim v_Result As Variant
Set obj_Shell = CreateObject("WScript.Shell")
'Reads the registry key that determines whether 'Show pictures' Internet Explorer advanced setting is enabled
v_Result = obj_Shell.RegRead("HKEY_CURRENT_USER\Software\Microsoft\Internet Explorer\Main\Display Inline Images")
Select Case v_Result
Case "yes" 'Pictures are displayed
If EnabledStatus = False Then _
obj_Shell.RegWrite "HKEY_CURRENT_USER\Software\Microsoft\Internet Explorer\Main\Display Inline Images", "no", "REG_SZ"
Case "no" 'Pictures are not displayed
If EnabledStatus = True Then _
obj_Shell.RegWrite "HKEY_CURRENT_USER\Software\Microsoft\Internet Explorer\Main\Display Inline Images", "yes", "REG_SZ"
Case Else
ScrapingCancelled = True
End Select
End Sub
No images loaded:
ShowPictures (0)
Images loaded:
ShowPictures (1)
A good practice is to set value to 1 in the end of macro.
I was searching a lot on the web and found your website very helpfull - that is why I have not posted anything yet, just reading.
However, I need your advice in the following step of my project. The porject is to automate the creation/placing of ad for selling goods.
The website is http://olx.bg/adding/
What I am failing to do through VBA is to press the blue square called "ДОБАВИ СНИМКА" which stands for "ADD PHOTO" in the form.
Once pressed a default BROWSE window opens to select the file.
Thanks in advance!
Add two references to your VBA project:
Microsoft Internet Controls
Microsoft HTML Object Library
The HTML behind the button has an id = add-files which makes it pretty easy to locate using getElementById
Here is a working example:
Sub PushAddPhotoButton()
Dim IEexp As InternetExplorer
Set IEexp = New InternetExplorer
IEexp.Visible = True
IEexp.navigate "http://olx.bg/adding/"
Do While IEexp.readyState <> 4: DoEvents: Loop
Dim photoButton As HTMLInputElement
Set photoButton = IEexp.Document.getElementById("add-files")
If (Not photoButton Is Nothing) Then
photoButton.Click
Else
MsgBox "Button not found on web page."
End If
IEexp.Quit
Set IEexp = Nothing
End Sub
If your IE security settings are on 'High' for Internet then you won't get a dialog or an error. The IE window will simply flash and then be gone.
Change to:
I'm trying to create a toolbar in Internet Explorer 8 & 9. The main functionality of this is to launch a in-house product when clicked on the icon and convert document accordingly. However, I'm having some difficulty using mshtml.HTMLDocument. Please take a look at my code and advise.
Thanks for helping out
' Get the hWnd value of the IE window that the macro button was clicked within
myhWnd = GetForegroundWindow()
MsgBox(myhWnd)
' for all IE window within the shell window, by the way this
' includes Windows Explorer as well as IE windows!
Dim IE As New SHDocVw.InternetExplorer
Dim SWs As New SHDocVw.ShellWindows
For Each IE In SWs
Doc = IE.Document ' Set the active document
Functions.OutputDebugString("setting active document for printing using set Doc in main")
If TypeOf IE.Document Is mshtml.HTMLDocument Then ' if the document is IE then proceed because EXPLORER window returns in the same group - (This is where I'm having trouble. It keep saying 'Document is not an HTML)
MsgBox("I'm here")
If (IE.HWND = myhWnd) Then ' ENABLE IT AFTER TESTING
Functions.OutputDebugString("JOB SUBMITTED TO QUEUE NOW. PLEASE WAIT.DO NOT CLICK BUTTON AGAIN TO INCREASE SPEED OF OPERATION...")
IE.StatusText = "JOB SUBMITTED TO QUEUE NOW. PLEASE WAIT.DO NOT CLICK BUTTON AGAIN TO INCREASE SPEED OF OPERATION..."
Functions.OutputDebugString("Verifying if the page is still downloading or not.. Do not process if its still downloading, wait in loop for 500 mili seconds")
If Not (IE.Busy = True) Then ' if IE is not currently downloading page then proceed
loopBackfromBusy:
Functions.OutputDebugString("Check in registry about exclusing access to printer")
processFlag = saveFileName(IE.LocationName, Doc.url) ' pass the document URL to give user more informative error messages.
Functions.OutputDebugString("Form_Load() - process flag = ")
If processFlag = True Then ' if no other window is printing then proceed
Functions.OutputDebugString("FILE SUBMITTED FOR PRINTING in form load")
IE.StatusText = "FILE SUBMITTED TO PRINTER FOR PRINTING. DO NOT CLICK BUTTON AGAIN AND WAIT FOR OPERATION FINISH..."
Functions.OutputDebugString("Initializing printer settings using initializeValues()")
intilizeValues(Doc.title) ' initialize printer settings and set everything ready for printer
DefaultPrinter = Printer.PrinterName ' store current default printr name
MsgBox(PrinterName)
Functions.OutputDebugString("Changing current default printer to Print Driver.. Note that this name is case sensitive and must be available on user machine or this software will not work correctly...")
SetDefaultPrinterMyWinNT(PrinterName) ' set the default printer to KC
Functions.OutputDebugString("Fired printing using default IE command")
IE.ExecWB(17, 0) '.... print the document silently
Else
MsgBox("Document is not an HTML document")
End If
The issue is here : If TypeOf IE.Document Is mshtml.HTMLDocument . It keep saying document is not an HTML document. I'll appreciate any suggestion or recommendation.
UPDATE :
Have changed the If condition to
If IE.Name = "Windows Internet Explorer" Then
If (IE.HWND = myhWnd) Then
MsgBox(IE.locationURL)
The above works fine however its not executing the code after which is
IE.StatusText = "JOB SUBMITTED..."
I decided not to check via this If TypeOf IE.Document Is mshtml.HTMLDocument. This worked If IE.Name = "Windows Internet Explorer"
My requirement is i need to have a VBA code in excel which runs to do some action in excel when a link in webpage is clicked.For example when i click a link "login" in webpage my VBA code should press printscreen button in keyboard(like we use sendkeys).
I have been searching for this solution since two weeks over google but failed to get one.This is urgent project requirement, please save my day,thank you very much in advance.
Here's an edited version of an answer I gave to a similar question (http://stackoverflow.com/questions/12877872/possible-to-intercept-onchange-event/12927960#12927960).
Project references set for "Microsoft HTML object library" and "Microsoft internet controls"
In a class module "clsEvents":
Option Explicit
Public WithEvents href As MSHTML.HTMLAnchorElement
'Note that having defined "href" as "WithEvents", if you choose "href"
' from the left-hand dropdown at the top of the class code module
' then the right-hand dropdown will populate with events you can select
' from to create an event-handling procedure in the class
Private Function href_onclick() As Boolean
Debug.Print "link clicked"
href_onclick = False 'cancels the navigation
End Function
In a regular module:
Option Explicit
Dim evt As clsEvents
Sub Setup()
Dim IE As New InternetExplorer
Dim el2 As Object
Set evt = New clsEvents
IE.Visible = True
IE.navigate "http://www.csee.wvu.edu/~riggs/html/select_example.html"
Do While IE.Busy
Loop
Set el2 = IE.document.getElementsByTagName("a")(1)
If Not el2 Is Nothing Then
Debug.Print "setting event capture on link:" & el2.innerText
Set evt.href = el2
End If
End Sub
If you run the Setup sub and then click the "Javascript" link on the page in IE you should see output in the Immediate window of the VB editor.
Hope that helps get you started.
There is nothing native you can do inside Internet Explorer to enable this functionality.
You would need to write an ActiveX control (using C#, C++, VB6, etc.), which would perform the Excel automation.
A few useful links:
How to automate Excel from VB6
How to write an updatable ActiveX control in VB6