How to Use VBA for Email in Access
- 1). Click the "Database Tools" tab, click "Visual Basic," and click the "Insert" menu. Click "Module" to insert a new VBA code module.
- 2). Click the "Tools" menu and click "References". Check the box next to "Microsoft Outlook <version number> Object Library" and click "OK".
- 3). Create a new sub procedure to and define the Outlook objects by adding the following VBA code:
Private Sub createEmail()
Set outlookApp = CreateObject("Outlook.Application")
Dim myItem As Object
Set myItem = outlookApp.CreateItem(olMailItem) - 4). Create a new email item by adding the following code:
myItem.Subject = "email subject"
myItem.Body = "mail message"
myItem.To = "myname@myemail.com"
myItem.Send - 5). Edit the previous Step and enter a valid email address next to "myItem.To" to send the email. Type "End Sub" to end the procedure and press "F5" to run your procedure and send the email using Outlook.
- 6). Read email in your Inbox folder and display it in your Immediate window by creating the following sub procedure:
Private Sub checkEmail()
Set OLApp = CreateObject("Outlook.Application")
Set MAPIs = OLApp.GetNamespace("MAPI")
Set outlookFolder = MAPIs.GetDefaultFolder(olFolderInbox)
For Each myMail In outlookFolder.Items
Debug.Print myMail.Subject
Debug.Print myMail.Body
Next myMail
End Sub - 7). Press "F5" to execute the procedure.