outlook vba sample
Here's a simple Outlook VBA (Visual Basic for Applications) example that demonstrates how to create a new email and send it using VBA in Microsoft Outlook. This is a basic script that can serve as a starting point for more advanced automation tasks in Outlook.
1. Open Outlook.
2. Press
Alt
+
F11
to open the Visual Basic for Applications (VBA) editor.
3. In the VBA editor, create a new module by clicking "Insert" > "Module."
4. Copy and paste the following code into the module:
vba
Sub SendEmail()
Dim OutlookApp As Object
Dim OutlookMail As Object
' Create a new instance of Outlook
Set OutlookApp = CreateObject("Outlook.Application")
' Create a new email item
Set OutlookMail = OutlookApp.CreateItem(0)
' Set email properties
With OutlookMail
.To = "recipient@example.com"
.CC = "cc@example.com"
.BCC = "bcc@example.com"
.Subject = "Sample Email Subject"
.Body = "This is the body of the email."
' .HTMLBody = "<HTML><BODY>HTML email body</BODY></HTML>" ' Uncomment this line to send HTML-formatted email
.Attachments.Add "C:\path\to\attachment.txt" ' Replace with the actual file path
.Send
End With
' Clean up objects
Set OutlookMail = Nothing
Set OutlookApp = Nothing
End Sub
5. Customize the email properties:
- Replace
"recipient@example.com"
,
"cc@example.com"
, and
"bcc@example.com"
with the recipient email addresses. You can leave these empty if not needed.
- Modify the email subject and body as needed.
- You can also send an HTML-formatted email by uncommenting and customizing the
.HTMLBody
line.
- To attach a file, replace
"C:\path\to\attachment.txt"
with the actual file path.
6. Close the VBA editor and return to Outlook.
7. Run the macro by pressing
Alt
+
F8
, selecting "SendEmail," and clicking "Run."
This VBA script creates a new email in Outlook and sends it. You can adapt and expand upon this example to perform more advanced tasks in Outlook, such as automating email processing, calendar events, or contact management.