How to do late binding in VBA?

Franco Sica picture Franco Sica · Nov 1, 2017 · Viewed 8k times · Source

I have this little function that achieves the creation of an email via VBA,
It gets the data from another function that works together with an Excel file.

The problem I have is that I made all this thru Excel 2016, and when some of my colleagues try to use it there an error of missing references (Outlook Library 16.0).

So I looked in the internet solutions and the ones I found are many, but the better is Late Binding. I have read all about it but I don't seem to really understand what's going on and how to make it work in the following code.

Sub EscalateCase(what_address As String, subject_line As String, email_body As String)

    Dim olApp As Outlook.Application
    Set olApp = CreateObject("Outlook.Application")

        Dim olMail As Outlook.MailItem
        Set olMail = olApp.CreateItem(olMailItem)

        olMail.To = what_address
        olMail.Subject = subject_line
        olMail.BodyFormat = olFormatHTML
        olMail.HTMLBody = email_body
        olMail.Send

    End Sub

Therfore, maybe you can help me out with this example in order to see it this practical case of mine.

Answer

CallumDA picture CallumDA · Nov 1, 2017

This is early binding:

Dim olApp As Outlook.Application
Set olApp = New Outlook.Application

And this is late binding:

Dim olApp As Object
Set olApp = CreateObject("Outlook.Application")

Late binding does not require a reference to Outlook Library 16.0 whereas early binding does. However, note that late binding is a bit slower and you won't get intellisense for that object.