Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to do late binding in VBA?

I have a function that creates an email via VBA.

I made this through Excel 2016. When some of my colleagues try to use it there an error of missing references (Outlook Library 16.0).

I looked in the internet for solutions and found the best is Late Binding. I have read about it but I don't understand how to make it work in the following example 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
like image 490
Franco Sica Avatar asked Dec 02 '22 12:12

Franco Sica


2 Answers

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.

like image 149
CallumDA Avatar answered Jan 22 '23 10:01

CallumDA


As Callum pointed out, late binding involves changing your application reference to an object and not setting a reference to the library.

Without a reference Excel doesn't know anything about Outlook until runtime. This also means that not only will intellisense not work, the constant names for values in Outlook won't work either.

e.g. In Outlooks Immediate window if you type Application.CreateItem( you'll get a whole load of item types pop up to choose from. olContactItem for instance.

Excel hasn't a clue what olContactItem means - it's an Outlook constant that only Outlook or an application with a reference to Outlook understands.

In Outlooks immediate window type ?olContactItem and it will return 2. That's the number you need to use instead of the constant name.

So your code changes from
Application.CreateItem(olContactItem) to olApp.CreateItem(2)

You need to do this throughout your code.

like image 34
Darren Bartrup-Cook Avatar answered Jan 22 '23 10:01

Darren Bartrup-Cook