This way of referring to objects is called "Early" and "Late Binding". From MSDN:
The Visual Basic compiler performs a process called binding when an object is assigned to an object variable.
An object is early bound when it is assigned to a variable declared to be of a specific object type. Early bound objects allow the compiler to allocate memory and perform other optimizations before an application executes.
By contrast, an object is late bound when it is assigned to a variable declared to be of type Object. Objects of this type can hold references to any object, but lack many of the advantages of early-bound objects.
You should use early-bound objects whenever possible, because they allow the compiler to make important optimizations that yield more efficient applications. Early-bound objects are significantly faster than late-bound objects and make your code easier to read and maintain by stating exactly what kind of objects are being used.
TL DR:
The difference is that in early binding you get intellisense and compiling time bonus, but you should make sure that you have added the corresponding library.
- Example usage of late binding:
Sub MyLateBinding()
Dim objExcelApp As Object
Dim strName As String
'Definition of variables and assigning object:
strName = "somename"
Set objExcelApp = GetObject(, "Excel.Application")
'A Is Nothing check:
If objExcelApp Is Nothing Then Set objExcelApp = CreateObject("Excel.Application")
'Doing something with the Excel Object
objExcelApp.Caption = strName
MsgBox strName
End Sub
- Example usage of early binding:
First make sure that you add the MS Excel 16.0 Object Library from VBE>Extras>Libraries:
Sub MyEarlyBinding()
Dim objExcelApp As New Excel.Application
Dim strName As String
'Definition of variables and assigning object:
strName = "somename"
'A IsNothing check:
If objExcelApp Is Nothing Then Set objExcelApp = CreateObject("Excel.Application")
'Doing something with the Excel Object
objExcelApp.Caption = strName
MsgBox strName
End Sub
Related articles: