Vba send email
Here is a basic example of how to send an email using VBA in Excel:
Step 1: Enable the Outlook Object Library
In the Visual Basic Editor (VBE), go to Tools > References and check the box next to "Microsoft Outlook XX.X Object Library" (where XX.X is the version of Outlook you have installed).
Step 2: Create a new module
In the VBE, go to Insert > Module to create a new module.
Step 3: Write the code
Paste the following code into the new module:
Sub SendEmail()
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 from Excel using VBA."
.Send
End With
' Clean up
Set olMail = Nothing
Set olApp = Nothing
End Sub
Step 4: Run the code
To run the code, click the "Run" button or press F5. The email will be sent to the recipient specified in the code.
Tips and Variations
- You can customize the email properties (e.g.
To
,Subject
,Body
) to suit your needs. - You can use the
Attachments
property to add attachments to the email. - You can use the
CC
andBCC
properties to specify carbon copy and blind carbon copy recipients. - You can use the
Priority
property to set the priority of the email. - You can use the
Display
method instead ofSend
to display the email in the Outlook client instead of sending it.
Error Handling
- Make sure to handle errors properly by using
On Error
statements and error handling routines. - Check the
Err
object to determine the type of error that occurred.
Security Considerations
- Be careful when sending emails using VBA, as it can be a security risk if not used properly.
- Make sure to validate user input and use secure methods to send emails.