2
votes

I am using VBA from Excel (Office 2010) to navigate through a webpage in Internet Explorer. My problem is I cannot declare an instance of an HtmlElement e.g.

Dim myHtmlEl As HtmlElement

Returns the error "User defined type not defined."

I have seen this problem before when I wanted to declare and instance of an InternetExplorer object. The solution to that was to create reference by Tools >> References... >> Microsoft Internet Controls in the VBA editor. My understanding is that Microsoft Internet Controls is a .dll with a definition of the InternetExplorer class.

Therefore to create an instance of an HtmlElement object I need to reference the .dll that defines that class. MSDN suggests that the .dll is System Windows Forms. I linked that but the class is still undefined.

How do I know which .dll contains HtmlElement class?

1
Add a reference to "MicroSoft HTML Object Library"Tim Williams
If for some reason Tim's reference does not work for early-binding, you could try late-binding Dim myHtmlEl As Object.Mike
Works. But how do you look up which reference I need to connect?cheezsteak
There's no short-cut to finding which reference you need to add, but if you google "VBA HTMLelement" you will likely find the answer in the first half-dozen hits.Tim Williams

1 Answers

3
votes

A late binding solution may suit your needs.

Dim myHtmlElement As Variant 
Dim IE As Variant 

Set IE = CreateObject("InternetExplorer.Application") 
IE.Visible = True 

IE.Navigate "http://www.stackoverflow.com/" 

' Wait while site is loading
While IE.Busy: DoEvents: Wend

' Get An Element
Set myHtmlElement = IE.Document.getElementById("myInput") 

' Set the value of an element
If Not myHtmlElement Is Nothing Then myHtmlElement.Value = ActiveCell.Value

' Click a button
Set myHtmlElement = IE.Document.getElementById("searchButton") 
myHtmlElement.Click

' Wait while site is loading
While IE.Busy: DoEvents: Wend

' Navigate the IE object 
Dim i As Integer 
For i = 0 To IE.Document.getElementsByTagName("a").Length - 1 
    If IE.Document.getElementsByTagName("div").Item(i).innerText Like "ab*" Then 
        ' Do Something
    End If
Next

Above code is based upon the linked MSDN forum.