To make the following code work, you'll need to include the "Microsoft Internet Controls" library in your VBA references first.
Go to your Visual Basic Editor, Menu
Tools -> References... and select the entry "Microsoft Internet Controls". If you can't find it in the list of available references, search for a file named shdocvw.dll, usually to be found in your Windows directory, subfolder System32.
Alternatively, you can skip the referencing and use late binding, defining the pointer to the Internet Explorer instance as
Object instead of SHDocVw.InternetExplorer in your VBA code. But then you'll miss out on a lot of goodies like intellisense, full access to the object model via the object browser, access to the application's built-in constants, and a popup listing all the supported constants upon typing...Before you can do anything with the Internet Explorer, of course you'll need one, and you'll need something to address it. The following function achieves exactly this by creating a new instance of the Internet Explorer and returning a pointer to it.
|
The next function loads a webpage:
|
But what if the desired page has already been loaded and you just want to use it?
The following function returns a pointer to an already open instance of the Internet Explorer, if it has the desired page loaded. It'll find it by comparing this page's URL with the URLs of open pages in the Internet Explorer. If the page could not be found, the function returns
Nothing. |
Sometimes, when you enter an URL to load a page, you'll get redirected, and thus the URL changes. Or your site uses frames and has the same URL for different content, so you can't clearly identify a page by its URL. Then you could check the title of the page instead:
|
Now that you have your web page (either by loading it new, or by accessing an already opened page), you can extract information from it, or manipulate the document or do whatever you want/need to do.
To make work with html documents easier, the Document object itself is just the root of a hierarchy of objects (and arrays of objects) that represent the different html tags in the document with all their properties and content. So if you need to address a certain element, you wont have to parse the html source, but you can quite easily address the element directly by its name or index.
A good introduction about how to work with the DOM (Document Object Model) and how to use it with forms in particular is given on this German site: Tagmodell des Webbrowsers
Here's a link to a full reference about the document object and all elements in there.
Last but not least, a very good and comprehensive but also German site is the SELFHTML DOM reference
And because an example often is easier to understand than long-winded explanations: the following example goes to Wikipedia, enters a search string and navigates to the search result.
|
Of course an Internet Explorer Object doesn't only contain the Document object. There's a lot more, and you can find an overview by going to your VBA editor and pressing
F2. This will open the object browser, where you can look for library SHDocVw, class InternetExplorer, and you'll find a list and short description of all methods, properties and events of this class.
← Ctrl← Alt
Ctrl →Alt →
Anonymous
July 18 2009, 10:31:37 UTC 2 years ago
Run time error 91
hi vba_corner,i was trying to use your code above (with minimal revision) but i've encountered "Run time error 91" Object variable or With block variable not set, when i press debug, it highlighted ".getElementsByName("code")(0).Value = myTextName
I don't have any programming background, most of the codes i'm using was derived from examples i've read and i just modify it until i got what i want (trial and error).. hope you could help me resolve this error...
thanks,
whel from the Philippines...
July 20 2009, 08:15:42 UTC 2 years ago
Re: Run time error 91
Hi,without seeing more of your code I can't say much, but basically, getElementsByname is a method of a Document object, and the error message says that your code didn't state the object you would want to use this method with.
Assuming that myIE contains a reference to an Internet Explorer Object, the code should look like:
With myIE.Document
.getElementsByName("code")(0).Value = myTextName
End With
or just
myIE.Document.getElementsByName("code")(0)
Hope this helps :)
Anonymous
September 30 2009, 16:41:17 UTC 2 years ago
navigate to a spacific point on a long web page
Hi,How can I navigate to a specific point on a webpage automatically. Manually, I have to scroll down to go to that point.
Thanks.
October 6 2009, 07:23:26 UTC 2 years ago
Re: navigate to a spacific point on a long web page
Hi, I'm sorry but I'm not very familiar with automating webpage access and the DOM model, but if you want to scroll to a link you could use the method .focus for that anchor object - this should give focus to the link and thus scroll down to the place where the link is. If you want to go to another type of object, I'm not sure if there's something similar or if there's a scroll method or something, but if there is, Google will probably find it :o)Anonymous
1 year ago
Anonymous
October 5 2009, 19:26:54 UTC 2 years ago
Downloading from IE using VBA
Hi VBA Corner,The code that you have given here works well on cases where we are searching for a particular text on a field. Can you please help with the code on finding a specific link and enabling a download from that link? My requirement here is to automate a download process from a site. The site in itself has several links and i need to navigate to one of the links and look for a particular file and download it.
Any help on this would greatly help. Thanks a lot.
October 6 2009, 07:31:46 UTC 2 years ago
Re: Downloading from IE using VBA
Hi,you could use the .document.links collection to go find your link. The links (anchor objects) have properties that help to identify the one you want, e.g. .innerText gives you the text that is displayed for the link, .href gives the URL of the link.
As I'm not to familiar with webpage scripting, I can't really give a code example here on the fly, but another perhaps useful method is .focus that sets the focus to the link, and perhaps .click works to follow the link and thus start the download? Or perhaps using navigate to go to the URL you found out with .href?
Anonymous
January 18 2010, 16:27:22 UTC 2 years ago
Click OK button automatically while Pop-UP message appear.
Hello All,Can you please help me in IE Automation, the problem is when i am running the automation a Pop-up message will appear. I want the POP-Up (Click "OK" button) Message has to click automatically.
Thanks in advance
Regards,
Vinod Kumar. S
vinodgo@gmail.com
January 20 2010, 10:25:19 UTC 2 years ago
Re: Click OK button automatically while Pop-UP message appear.
If the OK button on the popup is the default button, and the popup gets focus when it pops up (which it probably does), you could use SendKeys to send the equivalent of pressing Return and thus close the popup.Anonymous
2 years ago
2 years ago
Anonymous
1 year ago
Anonymous
February 2 2010, 06:38:29 UTC 2 years ago
Place final URL link in a cell from Indirect URL
What method or how would I be able to receive the final complete URL from a website by first submitting an indirect link.Example:
Indirect URL
http://bit.ly/bVlLHr (is the indirect URL to the Main URL)
Main or Direct URL is
http://www.handbag.com/celebrity/Brangel
So I would have a function that would lets say do the following:
DirectURL(Range("a1").value) (A1 = "http://bit.ly/bVlLHr") OR DirectURL("http://bit.ly/bVlLHr")
The Result would be
"http://www.handbag.com/celebrity/Brange
I have been searching for so long. Any help would be very much appreciated. :)
Nicole
February 5 2010, 14:31:26 UTC 2 years ago
Re: Place final URL link in a cell from Indirect URL
Hi, the follwing function opens a new Internet Explorer, loads the page with the indirect URL and then returns the URL of the loaded page, which is the direct URL.But I'd not use this function directly in a cell on a worksheet because every time Excel recalculates the sheet, it would connect to the Internet and load the web page.
'loads a web page and returns the URL it might redirect to
Function DirectURL(IndirectURL As String) As String
Dim myIE As SHDocVw.InternetExplorer
'create new IE instance
Set myIE = New SHDocVw.InternetExplorer
'open page
myIE.Navigate IndirectURL
'wait until IE finished loading the page
Do While myIE.ReadyState <> READYSTATE_COMPLETE
Application.Wait Now + TimeValue("0:00:01")
Loop
'read direct URL
DirectURL = myIE.Document.URL
'close browser
myIE.Quit
Set myIE = Nothing
End Function
Anonymous
2 years ago
Anonymous
February 15 2010, 18:09:47 UTC 2 years ago
Problems with html import from IEobject
Hi there!thx for this site, thats exactly what I need! I have a problem with exporting a website. I create an object and initialize a variable named "objIE" with the IEobject. The main problem is a runtime error, which tells me i havent declare the variable "varDivs", since I have initialized it with "ObjIE.Document.All.tags("TABLE")". The variable varDivs is a object, but with no content! Now the funny thing is: If i go through the code manually with the debugger, thers no bug popping up. If I execute it without breakpoints it works! The site is loaded completely and shows the correct content. I have tried to delayed the process with sleeps() but it does not work. What am I doin wrong? :(
Heres the excerpt:
Set ObjIE = CreateObject("InternetExplorer.Applicati
Set varDivs = GoogleObjIE.Document.All.tags("DIV")
For Each varDiv In varDivs
If varDiv.ID = "foo" Then
Set varTables = ObjIE.Document.All.tags("TABLE")
For Each varTable In varTables
' Use the innerText to see if this is the table we want.
If varTable.ID = "foobar" Then
'here comes the bug! no access to varTable.ID because varTable is empty!
Set varRows = varTable.Rows
lngRow = 2 'This will be the first output row
For Each varRow In varRows
Set varCells = varRow.Cells
lngColumn = 1 'This will be the output column
For Each varCell In varCells
If IsNumeric(varCell.innerText) Then
' do something
End If
lngColumn = lngColumn + 1
Next varCell
lngRow = lngRow + 1
Next varRow
End If
Next varTable
End If
Next varDiv
A big thx !
greetz Ali
February 18 2010, 14:18:57 UTC 2 years ago
Re: Problems with html import from IEobject
You create an ObjIE, but the varDivs go to GoogleObjIE - is the naming wrong or did you initialize that one somewhere else?Anonymous
2 years ago
Anonymous
March 2 2010, 21:59:58 UTC 2 years ago
Trouble inputing data directly to already existing webpage.
I've been playing with this code for a few hours now and can't seem to get it to work for me (new at this).My goal is to send text to a specific textbox on an already open webpage. I've found many examples that can do this but they all have to open a new instance of the page. For testing I've just been using Google's homepage.
If possible could somebody please lend me a hand and post a working example of how to input text into the Search box on and already open instance of Google.
Thanks in advance!
Anonymous
July 9 2010, 16:26:56 UTC 1 year ago
Re: Trouble inputing data directly to already existing webpage.
'find the right internet explorer webpageDim allExplorerWindows As New SHDocVw.ShellWindows
Set allExplorerWindows = New SHDocVw.ShellWindows
Dim IEwindow As SHDocVw.InternetExplorer
Dim foundFlag As Boolean
foundFlag = False
For Each IEwindow In allExplorerWindows
If InStr(IEwindow.LocationURL, ".direct-access.us") <> 0 Then
foundFlag = True
Exit For 'found the right IE window URL
End If
Next
If Not foundFlag Then
DisplayBox = MsgBox("Could not find an open instance of xxx." _
& vbNewLine & vbNewLine & " " & _
"You can contact the program author if assistance is needed.", _
vbOKOnly + vbMsgBoxSetForeground, "Please try again.")
GoTo Exit_Get_Employee_Statuses
End If
IEwindow.Visible = True
'end find
'get the pages entire main IE document
Dim mainDoc As HTMLDocument
Set mainDoc = IEwindow.document
mainDoc.all("UserID").value = 12345
mainDoc.all("Submit").click
'if you do a program break you can use 'debug.print mainDoc.documentelement.innerhtml' in the immediate window to find the controls
March 18 2010, 10:53:57 UTC 2 years ago
How to close the Last opened Window
Thanks for the great code !After opening the window using:
Function LoadWebPage(i_IE As SHDocVw.InternetExplorer, _
i_URL As String) As Boolean
With i_IE
'open page
.Navigate i_URL
'wait until IE finished loading the page
Do While .ReadyState <> READYSTATE_COMPLETE
Application.Wait Now + TimeValue("0:00:01")
Loop
'check if page could be loaded
If .Document.URL = i_URL Then
LoadWebPage = True
End If
End With
End Function
is there a way to close this window from Excel VBA msgbox ?
e.g
I run a vba function. the function pops the browser window and asks via a msgbox - "close the window?" when Yes is clicked, I would like to close the window .
thanks for reply !!
March 19 2010, 12:03:51 UTC 2 years ago
Re: How to close the Last opened Window
Sure there's a way :o)You'll need your reference to the Explorer and then you can close it with the method Quit, e.g. like this:
myAnswer = MsgBox("Close Explorer?", vbYesNo)
If myAnswer = vbYes Then myIE.Quit
If you have several tabs open, Quit will only close the respective tab and not the entire browser.
2 years ago
2 years ago
2 years ago
2 years ago
2 years ago
2 years ago
2 years ago
Anonymous
May 17 2010, 08:30:40 UTC 2 years ago
How to continue processing in VBA after clicking a link has opened another IE window?
Hi there,I have been working on some VBA code that will auto-populate some fields on a website, invoke a search there, then return the results to Excel. However, one page of the website opens a second IE window to perform a secondary search, then populates the original window with the user-selected value from the secondary search. The resulting value is not user-editable in the original window.
Through the DOM I invoke a click on the original window. This opens the second window, but the .click statement never completes. At this point my VBA freezes and eventually reports the message “Microsoft Office Excel is waiting for another application to complete an OLE action.”
Even if I put a stop statement directly after the click, it is not reached. I can only get the code to continue by manually entering values into the second window.
I want to be able to manipulate the fields on this secondary window using VBA, and then close it to populate the values in the original. But I can’t get past the original click.
The code snippet is as follows:
Set objCollection2 = objElement.nextSibling.getElementsByTagN
For Each objElement2 In objCollection2
If InStr(1, objElement2.src, pstrImage, vbTextCompare) > 0 Then
If objElement2.parentNode.tagName <> "A" Then
Err.Raise gcErrUnexpectedXMLStructure, , "Unexpected XML Structure - no a tag owning img"
Else
objElement2.parentNode.Click ‘<==VBA stops running at this point
Stop ‘<==NEVER REACHES THIS POINT
GoTo DISQISClickIcon_Exit 'this is the only valid exit from this sub
End If
End If
Next objElement2
Any suggestions on how to overcome this would be much appreciated. I think that the click is invoking javascript code to open the new window - I can supply the XML source if it helps.
Thanks!
Anonymous
May 17 2010, 15:33:39 UTC 2 years ago
Code not finding text fields
Great tutorial, really useful information. I do seem to be having trouble with one particular web page though - I am trying to log in to this site: https://www.vcol.co.uk/home/default.vco?s****************************************
Sub ExplorerTest()
Const myPageTitle As String = "VCO Home Page"
Const myPageURL As String = "https://www.vcol.co.uk/home/default.vco?s
Const mySearchForm As String = "login_form"
Const mySearchInput As String = "email"
Const mySearchTerm As String = "Test"
Const myButton As String = "Go"
Dim myIE As SHDocVw.InternetExplorer
'check if page is already open
Set myIE = GetOpenIEByTitle(myPageTitle, False)
If myIE Is Nothing Then
'page isn't open yet
'create new IE instance
Set myIE = GetNewIE
'make IE window visible
myIE.Visible = True
'load page
If LoadWebPage(myIE, myPageURL) = False Then
'page wasn't loaded
MsgBox "Couldn't open page"
Exit Sub
End If
End If
With myIE.Document.forms(mySearchForm)
'enter search term in text field
.elements(mySearchInput).Value = mySearchTerm
'press button "Go"
'.elements(myButton).Click
End With
End Sub
Anonymous
June 14 2010, 11:06:22 UTC 1 year ago
File Download from Internet Explorer
Hi ,I'm trying to navigate to a web page and try to download a file from the url after clicking on a particular link.
The clicking on the link etc works perfectly however when the File Download dialog box ( Open , Save, Cancel ) appears , I want to get control on the box and save the file on a desired location .
Dont want to use sendkeys as its not 100% reliable .
I have searched everywhere but did not get any solution so far.
You can go to following link :
http://www.officetutorials.com/exceltuto
( Click on any tutorial which would open the file download dialog box )
Thanks in advance
Ram.
Anonymous
June 18 2010, 15:31:41 UTC 1 year ago
DOM Web Query
Hi guys,I would like to know how to adress an Internet Site (http://www.finanztreff.de/), type in a search term (e.g. BN47VG)and then click search and copy the output in my excel worksheet automatically.
This is the relevant part of the web site code, I suppose:
What changes should I make on the vba code presented above on this site for being able to adress the value "WKN / ISIN / Name" and type in my search term and click the search button?
Anonymous
July 3 2010, 22:38:08 UTC 1 year ago
how to copy HTML source of a website and paste it as a string in one cell ?
Hello.I'm sorry for my bad english. I'm really a newbie with VBA end i need too learn how to make these steps:
1) Copy an URL from a cell in excel
2) open IE
3) copy the URL in the link bar
4) get the HTML souce
5) paste the HTML source in a cell in excel
6) repeat the operation with onother URL in another cell (possibily using the same IE window i opened before or opening a new one after closing the previous session)
I really appreciate any help you will be so kind to give me.
Thank you so much.
I rell
Anonymous
September 8 2010, 11:57:38 UTC 1 year ago
How to click the link which will change for each candidate?
Hi,Could you please help me on the below issues.
1. When i login into website 1st window will have 3 tabs(img) and also it contain different Frame & Form name.
A. <td>
B. <td>
C. <td>
2. For each requisition number will have different title(in Link) so i need to click the link i.e the title name to move to other window. In this there will be different ID & Names.
<td nowrap="nowrap"><input ... > </td>
<td>
<td></td>
<td nowrap="nowrap">468314</td>
<td> </td>
<td width="100%">
</td>
Will appreciate if somebody help me in both the issue in IE Automation
Regards,
Vinod Kumar
Anonymous
September 8 2010, 12:03:14 UTC 1 year ago
How to click the link which will change for each candidate?
Hi,Could you please help me on the below issues.
1. When i login into website 1st window will have 3 tabs(img) and also it contain different Frame & Form name.
'<tr>
'<td>
'<td>
'<td>
'<td>
'<td>
'<td>
'<td width="100%"></td>
'</tr>
2. For each requisition number will have different title(in Link) so i need to click the link i.e the title name to move to other window. In this there will be different ID & Names.
'<td nowrap="nowrap"><input ... > </td>
'<td>
'<td></td>
'<td nowrap="nowrap">468314</td>
'<td> </td>
'<td width="100%">
'
'</td>
Will appreciate if somebody help me in both the issue in IE Automation
Regards,
Vinod Kumar
Anonymous
January 17 2011, 17:53:50 UTC 1 year ago
I am impressed! Blog information posted here is non-standard real my cohort
I am impressed! Blog information posted here is quite my friend. I neutral thirst for to clout board up with comments and nobility work. IE browser bookmarks to your blog solely now, I l come in arrears to drive my friends more in the future! The color of the layout is not bad, it is mild on the eyes.Anonymous
March 10 2011, 14:43:28 UTC 1 year ago
Re: I am impressed! Blog information posted here is non-standard real my cohort
WTF?!Anonymous
1 year ago
Anonymous
June 3 2011, 09:51:48 UTC 11 months ago
Excel VBA and IE integration
Hi,I am actually looking to automate a process which is done manually and is time consuming.
I have a list in my excel file after working on the list I update my comments in the same excel file on the same row. After I am done with all this, I have to open a web based application, Search of that particular line no and and then copy and paste my comments from the excel file to the web application.
Is there any way I can automate this using Excel VBA???
Anonymous
June 15 2011, 22:24:43 UTC 11 months ago
Close one tab of Internet Explorer
Hi,I managed to do "clicks" into a web page by using WebQueries, first I add a QueryTable into a worksheet, get the address of the link I want to click and then following it with the next line:
Selection.Hyperlinks(1).Follow NewWindow:=False, AddHistory:=True
The problem I have is that sometimes the "clicks" the program has to do are too many, with every click a new tab is opened so the maximum of tabs is reached and the program stops working because it can't open anymore tabs of the browser ...
What I want is a code that closes the new tab I opened once I don't need it anymore, but just that specific tab not the whole Internet Explorer, what can I do?
Anonymous
August 9 2011, 14:31:19 UTC 9 months ago
Title page within an IE window
Hi,I love your post it really helped me alot however now Im quite stuck.
the code blelow works just on most pages however there is a problem, as always ;),
The page Im trying to utilize this on has a Java popupform (it does not create new iexplorer window) that has a different title, therefore if I make it find "ssox" it tries to find it in the wrong place.
If I change the script to look for the popup with title "right place" it cant find it since it is not in its own explorer window rather it is an popup inside an ie window under the title "Wrong Place".
If I instead ask it to find "Wrong Place" it can find the correct IE window but it cat find "ssox" since it is not in the code under the title "Wrong Place".
Sub Button3_Click()
'find the right internet explorer webpage
Dim allExplorerWindows As New SHDocVw.ShellWindows
Set allExplorerWindows = New SHDocVw.ShellWindows
Dim IEwindow As SHDocVw.InternetExplorer
Dim foundFlag As Boolean
foundFlag = False
For Each IEwindow In allExplorerWindows
If TypeName(IEwindow.Document) = "HTMLDocument" Then
'check the title
If IEwindow.Document.Title = "Wrong Place" Then
'If IEwindow.Document.Title = "Right Place" Then
Dim mainDoc As HTMLDocument
Set mainDoc = IEwindow.Document
mainDoc.all("ssox").Value = "375"
Else
End If
End If
Next
End Sub
Anonymous
August 15 2011, 03:12:10 UTC 9 months ago
best sewing machine
This post is very useful for me, much appreciated! :)Anonymous
August 25 2011, 19:22:08 UTC 9 months ago
Select a Listbox in IE
Hi,VBA Corner!I'm having trouble trying to select a item from listbox of one site. Below its the code of the listbox:
<select ... >
<option ... >Choose one
<option ... >BROWN
<option ... >BLOND
<option ... >RED
How can I select any option on the list above using VBA/EXCEL?
Thanks on advance!
varellanet@hotmail.com
August 30 2011, 22:41:48 UTC 8 months ago
Working with Internet Explorer Using VBA
Hi Vba_corner,refering your below comment:
"(This was tested with IE6. Since IE7 uses tabs for different webpages instead of different windows, this code probably won't work for IE7.)"
If we are using IE7, how much change in your code will require..We are not Vba expert but trying to use our code in IE7 but not sure if we can modify your code based on IE7.
Thanks.
DW
August 31 2011, 08:30:32 UTC 8 months ago
Re: Working with Internet Explorer Using VBA
Hi DW,if you set your browser to open new pages in new tabs instead of new windows, the method navigate2 will open a new tab. If you want a new window, you'll need to create a new instance of IE, so the above code can be used for IE7 as well - when I posted this entry I didn't have IE7 to test, but in the meantime I had and tried it out a while ago :o)
Anonymous
October 5 2011, 04:22:50 UTC 7 months ago
Reusing same ie instance for multiple commands
Hi, I am trying to develop a form that I can input search text into and then provide multiple buttons to search various websites with the supplied text. Currently the code I use creates a new instance of IE for each button where I would prefer it to use the same IE instance and just navigate to the new url. Is there a way to have a IE instance created and then be able have each button perform a command like ie.navigate? ThanksOctober 6 2011, 15:15:05 UTC 7 months ago
Re: Reusing same ie instance for multiple commands
Hi, of course this is possible. After creating one instance of the Internet Explorer, keep the pointer to it in a variable that all buttons can access, for instance a global variable in the form. So each button can use that pointer and thus the same instance of IE.Anonymous
7 months ago
7 months ago
Anonymous
7 months ago
Anonymous
October 31 2011, 15:29:45 UTC 6 months ago
Unable to run the IE automation
Hi, Based on IE Automation i have developed some automation for my team. We received a mail from IT for Upgradtion of tool, next day my all IE automation are not working after the changes in the system background. When i checked all the TextBox, Link & URL names everything are same but i can't able to INPUT or EXTRACT data in the web page.**In our portal through automation i am able to login using the below coding:
IE.Document.all.Item("USER").Value
IE.Document.all.Item("password").Value
**I am facing the issue when it comes to the frame name:
IE.Document.frames("TargetContent").Docu
***ERROR MESSAGE***
Run-time error'-2147024891 (80070005)':
Access Denied
Kindly guide me. Thanks
Regards, Vinod Kumar
Anonymous
November 1 2011, 00:41:44 UTC 6 months ago
ie/ internet explorer state
Hi, I am using excel virtual keys to activate a webpage and then refresh it then run some code, the problem i have is that sometimes the internet page just keys loading and therefore my next code will not work as the page isn't loaded, I use a wintimer so that the script waits for 30 seconds before running the next part, however if ie is still loading then my script falls over and excel crashes.My first script is.
ActivateWindow "Internet Explorer"
KeyPlusKey 17, Asc("2") 'control+tab1
Key 116 'Refresh Page
I want it to wait from here until the page has finished loading and then it would do the following.
userform1.textbox1.value = "Loaded"
And then it could keep running my script from there.
If you could help with the script that is needed to wait for loading and then update the textbox it would be greatly appreciated.
← Ctrl← Alt
Ctrl →Alt →