VBA Intellisense and Early-binding vs Late-binding

Generally speaking, you want to use early binding, rather than late binding.

Early binding an object variable tells VBA specifically what we’ll be doing with it.
Late binding is generically declaring the variable an Object and VBA doesn’t know how we intend to use it.

 
VBA Intellisense helper menu
VBA Intellisense helper menu

Example of Early binding:
   Dim ie As InternetExplorer
   Set ie = New InternetExplorer

Advantages:
1) you get to use Intellisense
2) code runs faster
3) full access to object model
4) better error-checking

 

Example of Late binding:
   Dim ie As Object
   Set ie = CreateObject("InternetExplorer.Application")

Advantages:
1) can use variables for multiple purposes
2) better backwards compatability with previous VBA versions

 

I almost always perfer early-binding, having a clear advantage over late-binding. One exception, however, is that I’ll often declare a reuseable element object generically (Dim ele as Object) so that I can use it for multiple purposes. Like the following example where I use ele to capture an img element and then a div element:

Dim ele as Object unspecified Object variable, not bound to any particular use
Set ele = ie.document.getElementsByTagName("img")(3)
Debug.Print ele.src I just printed the source of an img!
For each ele in ie.document.getElementsByClassName("ytube")
    Debug.print ele.textContent I just printed the text of a div!
Next
 

But aside from mere convenience, there’s really no good reason to do it this way. Hence my advice to pretty much always use early binding.

 
Facebooktwittergoogle_plusredditlinkedintumblrFacebooktwittergoogle_plusredditlinkedintumblr