Reading web data with VBA from excel using Microsoft HTML Object Library and Microsoft Internet Controls

Pages: 1 2 3

This specific content was written 14 years ago. Please keep this in mind as it may be outdated and not adhering to best-practices.

Parsing the HTML

Sub getBalance()
    Dim lastValue As Object
    Dim last As String
    
    If oBrowser Is Nothing Or oBrowser.document Is Nothing Then
    Exit Sub
    End If
    
    
    
    For Each Item In oBrowser.document.all
        If Item.getAttribute("class") = "FieldValueNormal" Then
            last = Item.innerHTML
        End If
    Next
    
    If ActiveCell Is Nothing Then
    Exit Sub
    End If
     last = Replace(last, vbLf, "") 'replace linefeed
    last = Replace(last, Chr(9), "") 'replace tab
    last = Replace(last, " ", "") ' replace space
    last = Left(last, Len(last) - 1) 'remove currency
    ActiveCell.Value = (last * 1) 'set active cell
    
End Sub


Explanations

Note: document.all is deprecated and we should use getElementById ( http://msdn.microsoft.com/en-us/library/ie/ms537434%28v=vs.85%29.aspx )

Below we analyze various sections of the code with explanations.

Navigation and Loading

The code below displays an example of how to navigate the window to a specific URL and wait until the browser has finished loading. This is necessary so that no errors take place if we wish to click (or read) a DOM element before it has rendered.

oBrowser.navigate "http://website"

Do
    ' Wait till the Browser is loaded'
    Application.Wait DateAdd("s", 2, Now)
    Debug.Print (oBrowser.readyState)
    Debug.Print (oBrowser.LocationURL)
Loop Until oBrowser.document.readyState = "complete"

 

Interacting with Items: Clicking and Setting

oBrowser.document.all.Item("userName").Value = "USER"
oBrowser.document.all.Item("Pswd").Value = "PASSWORD"
oBrowser.document.all.Item("selectionList").selectedIndex = 1 
oBrowser.document.all.Item("login").Click

Above we have an example of 4 operations:

  • Setting the textfield with id userName to “USER”
  • Setting the passwordfield with id Paswd to “PASSWORD”
  • Setting the selection list with id selectionList to have selected the element with index=1
  • Clicking the button with id login

Conclusions and Reasoning follow on next page



Menelaos Bakopoulos

Menelaos Bakopoulos

Mr. Menelaos Bakopoulos is currently pursuing his PhD both at Center for TeleInFrastruktur (CTiF) at Aalborg University (AAU) in Denmark and Athens Information Technology (AIT) in Athens, Greece. He received a Master in Information Technology and Telecommunications Systems from Athens Information Technology and a B.Sc. in Computer Science & Management Information Systems from the American College of Thessaloniki. Since April 2008 he has been a member of the Multimedia, Knowledge, and Web Technologies Group.

More Posts