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.
Example of Early binding:
Dim ie As InternetExplorer
Set ie = New InternetExplorer
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")
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
Dim ele as Objectunspecified Object variable, not bound to any particular use
Set ele = ie.document.getElementsByTagName("img")(3)
Debug.Print ele.srcI just printed the source of an img!
For each ele in ie.document.getElementsByClassName("ytube")
Debug.print ele.textContentI just printed the text of a div!
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.