Access vba send outlook mail
Here is an example of how to send an Outlook email using VBA:
Step 1: Create a new module in the Visual Basic Editor
- Open Outlook and press
Alt + F11
to open the Visual Basic Editor. - In the Editor, click
Insert
>Module
to create a new module.
Step 2: Write the VBA code
-
In the new module, paste the following code:
Sub SendOutlookMail() Dim olApp As Object Dim olMail As Object ' Create a new instance of Outlook Set olApp = CreateObject("Outlook.Application") ' Create a new email Set olMail = olApp.CreateItem(0) ' 0 = olMailItem ' Set the email properties With olMail .To = "[email protected]" .Subject = "Test Email" .Body = "This is a test email sent using VBA." .Send End With ' Clean up Set olMail = Nothing Set olApp = Nothing End Sub
Step 3: Run the VBA code
-
Save the module by clicking
File
>Save
(or pressCtrl + S
). -
To run the code, click
Run
>Run Sub/User Form
(or pressF5
). -
The code will send an email to the recipient specified in the
To
property.
Tips and Variations
- You can customize the email properties (e.g.,
To
,Subject
,Body
) to suit your needs. - You can also add attachments to the email by using the
Attachments.Add
method. - If you want to send the email to multiple recipients, you can use a loop to iterate through an array of email addresses.
- You can also use the
SendUsingExchange
property to specify the Exchange server to use for sending the email.
Error Handling
- Make sure to handle any errors that may occur during the execution of the code. You can do this by adding error handling code, such as:
On Error GoTo ErrHandler ' Code here ErrHandler: MsgBox Err.Description, vbExclamation, "Error" Exit Sub End Sub