How to press Upload button through VBA - vba

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:

Related

Is there a way to open an IE window with a user-defined name. When same URL opened, already opened IE window comes to foreground

Here is my requirement which I intend to implement. There is one window application showing some icons which take me to different web sites. When I click on one of the icons, it should open an IE window and append a customized name to it.
So, before opening any website after I click on website icon, I want to check if there is already an IE window open with that customized name, if yes, bring that already opened window to the foreground. If not, open a new IE window.
I have checked various questions posted which are related to what I am looking to achieve, but am somehow not able to get it right. Below is my attempt.
For Each e In shellWins
If InStr(1, e.GetProperty("IEWindowName"), namedWindow, CompareMethod.Text) <> 0 Then
hWnd = e.HWND
myIE = e
End If
Next
If hWnd == -1
Dim p As New Process
Dim psi As New ProcessStartInfo(IEPath, webSiteURL)
p.StartInfo = psi 'Trying to open a new IE window
p.Start()
For Each ie In shellWins
If ie.hwdn = p.MainWindowHandle Then
ie.PutProperty("IEWindowName", namedWindow)
End If
Next
End if
Else
myIE.BringToForeground()
This sometime works and sometimes does not. Is there any better way to do it?
It doesn't work in which situation? Does there any error throw when it doesn't work? If there is, please tell us the detailed error information and in which line it occurs.
Besides, you could try to compare the url to check if the website is already open in IE like this:
Sub Main()
Dim shellWins As SHDocVw.ShellWindows
Dim explorer As SHDocVw.InternetExplorer
shellWins = New SHDocVw.ShellWindows
Dim SQuery As String = "https://www.example.com/"
For Each explorer In shellWins
If explorer.Application.Name = "Internet Explorer" And explorer.LocationURL.Contains(SQuery) Then
explorer.BringToForeground()
End If
Next
shellWins = Nothing
explorer = Nothing
End Sub

Windows Form run website without address bar

I've seen a lot of examples using JavaScript to run a popup window to remove address bar. My issue is I want to run a full website [that I've created in ASP.net] without the address bar visible from a Windows Form application.
I've tried:
Dim objIE As Object 'InternetExplorer 'or as object - if you want to keep it lite and don't add the reference
objIE = CreateObject("InternetExplorer.Application")
With objIE
.Visible = True
objIE.AddressBar = False
objIE.MenuBar = False
objIE.ToolBar = False
.Navigate2(Address)
End With
objIE.Navigate = Address
but I get an error at CreateObject of Cannot create ActiveX component.
So my current working code to run the website is:
Dim process As New System.Diagnostics.Process()
process.StartInfo.WindowStyle = System.Diagnostics.ProcessWindowStyle.Hidden
Dim sInfo As New ProcessStartInfo(Address)
Process.Start(sInfo)
However, the address bar is visible.
Any suggestions?
That code should work fine, as I just tested it myself. I would say start a fresh VB file (console application/windows form, whichever you'd like) and try to run just these:
Dim objIE as Object
objIE = CreateObject("InternetExplorer.Application")
With objIE
.Visible = True
End With
If it does not run from there, then your best bet is to try to "Reset" your internet explorer, which can be done through the Settings/Options. I've done this in the past and it allowed to work. The fact that you cannot create the object is the concerning part, as that's being written correctly and when I run that on my PC it works.
Give those two a shot (try a fresh file, and reset internet explorer). And let me know if that works.

VBA-Excel: Filling forms in an IE Window

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.getEleme‌ntById("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.

Internet Explorer 8/9 Add-On VB.Net - mshtml.HTMLDocument not working. Code enclosed

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"

VBA IE automation, To do events like displaying message,etc in excel when a link in webpage is clicked

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