Send an email when workbook is saved - vba

I am trying to send an email that will update users of changes to a spread sheet. I am trying to make it so that when the document is saved there will be an email automatically sent with a list of the changes.
Does anyone know if it is possible to automate email upon saving the document?

You can use this code here not fancy as Chip Pearson but easy to understand, This method also relies on using outlook:
Private Sub Workbook_BeforeSave(ByVal SaveAsUI As Boolean, Cancel As Boolean)
Dim Outlook As Object, EMail As Object
Set Outlook = CreateObject("Outlook.Application")
Set EMail = Outlook.CreateItem(0)
With EMail
.To = "EmailAddress1#Server.com; Email2#aol.com"
.CC = ""
.BCC = ""
.Subject = "Put your subject here"
.Body = "Add you E-Mail Message Here"
.Attachments.Add ActiveWorkbook.FullName ' To add active Workbook as attachment
.Attachments.Add "C:\Test.xlsx" ' To add other files just use path, Excel files, pictures, documents pdf's ect.
.Display 'or use .Send to skip preview
End With
Set EMail = Nothing
Set Outlook = Nothing
End Sub
To set this up Here is the full guide:
First open up the VBA window using ALT + F11 then Select Worbook on the window to the right, Then workbook from the drop down:
Then from the Drop down on the right Select BeforeSave:
Then paste your code there:
You should end with this:

It should be. You'll need to place your code in the Workbook_BeforeSave event, so it is triggered when the workbook is saved.
Chip Pearson has a good article on Sending E-mail from VBA

You need to put the code in ThisWorkbook code section. Workbook_BeforeSave event is triggered before workbook is save. Hope below code gives you an idea how it can be accomplished.
Private Sub Workbook_BeforeSave(ByVal SaveAsUI As Boolean, Cancel As Boolean)
' Identify here list of changes
' You can pass as a string to SendMail
Dim strChanges As String
strChanges = "test"
SendMail strChanges
End Sub
Sub SendMail(msg As String)
Dim iMsg As Object
Dim iConf As Object
Dim Flds As Variant
Set iMsg = CreateObject("CDO.Message")
Set iConf = CreateObject("CDO.Configuration")
iConf.Load -1
Set Flds = iConf.Fields
'Configure the below details
With Flds
.Item("http://schemas.microsoft.com/cdo/configuration/sendusing") = 2
.Item("http://schemas.microsoft.com/cdo/configuration/smtpserver") = "test-002"
.Item("http://schemas.microsoft.com/cdo/configuration/smtpserverport") = 25
.Update
End With
With iMsg
Set .Configuration = iConf
.To = "test#gmail.com"
.From = "test#gmail.com"
.Subject = "msg" & " " & Date & " " & Time
.TextBody = msg
.Send
End With
Set iMsg = Nothing
Set iConf = Nothing
End Sub

Related

Change placeholders in Subject

I'm trying to create a template where I can have VBA prompt me to change items in the subject. I've a template email with the subject line that should be Project / GC/Client, and in the template I've written that as #0# / #1#.
I'm at the below, but it's erroring.
Private Sub m_Inspector_Activate()
Dim Item As MailItem
Dim Value As String
If TypeOf m_Inspector.CurrentItem Is MailItem Then
Set mail = m_Inspector.CurrentItem
If mail.Subject = "subject" Then
Value = InputBox("Project")
mail.Subject = Replace(mail.Subject, "#0#", Value)
Value = InputBox("GC/Client")
mail.Subject = Replace(mail.Subject, "#1#", Value)
End If
End If
End Sub
This code is used on a template button in Outlook. i.e. the template file it is launching contains the subject line of #0# / #1#. Ideally, after the template launches, the macro prompts the user to update those two fields with the proper subjects.
Sub CommandButton1_Click()
Set MyItem = Application.CreateItemFromTemplate _
("V:\All Folders\Templates\Freebie.oft")
MyItem.Display
End Sub
If all that you really want to do is open a template and replace text in the subject line, this may work for you:
Sub CommandButton1_Click()
Call OpenTemplate
End Sub
Sub OpenTemplate()
Dim OutMail As Outlook.MailItem
Set OutMail = Application.CreateItemFromTemplate("V:\All Folders\Templates\Freebie.oft")
On Error Resume Next
With OutMail
.To = ""
.CC = ""
.BCC = ""
.Subject = Replace(.Subject, "#0#", InputBox("Project"))
.Subject = Replace(.Subject, "#1#", InputBox("GC/Client"))
.Display
End With
On Error GoTo 0
Set OutMail = Nothing
Set OutApp = Nothing
End Sub
If we can avoid using the Inspector then this is much simpler

Send an Email using PowerPoint VBA

I want to send an email (with subject, body...) to another email address.
I tried the following code, but it didn't work:
Private Sub CommandButton1_Click()
Dim ret As Boolean
Dim strAddress As String
Dim strMessage As String
strAddress = "examplemail#gmail.com"
ret = SendEMail(strAddress, (Label1.Caption), strMessage)
Label1.Caption = ret
If Label1.Caption = "True" Then
MsgBox "Mail sent!"
ElseIf Label1.Caption = "False" Then
MsgBox "Mail not sent!"
End If
End Sub
Public Function SendEMail(strRecipient As String, strSubject As String, strBody As String) As Boolean
Dim oApp As Object
Dim oMail As Object
Err.Clear
On Error Resume Next
Set oApp = GetObject(Class:="Outlook.Application")
If Err <> 0 Then Set oApp = CreateObject("Outlook.Application")
Err.Clear
Set oMail = oApp.CreateItem(0)
With oMail
.Subject = strSubject
.To = strRecipient
'copy to self
.CC = "youraddy#you.com"
.BodyFormat = 1
.Body = strBody
.Send
End With
'cleanup
Set oMail = Nothing
Set oApp = Nothing
'All OK?
If Err = 0 Then SendEMail = True Else SendEMail = False
End Function
The code was originally taken from here.
If it is possible, I want a code that is compatible with most PCs.
Using Microsoft Outlook
For sending an e-mail you need to have an e-mail account in Microsoft Outlook configured, because your code is using Outlook to send the e-mail.
Set oApp = GetObject(Class:="Outlook.Application")
Alternative 1: SMTP
Alternatively you could set up an SMTP connection in VBA to send the e-mails over an external mail server using CDO. More information on the usage of CDO in VBA can be found here (even if they write the code is for Excel, you can use it for PowerPoint as well) and here as well.
The drawback of this approach is, that the SMTP login credentials are visible in the VBA code. This could be a security issue if you plan to share this presentation with other people.
Alternative 2: Mailto-Link
A third way would be to offer the user a link to click on in order to send the e-mail: mailto:recipient#example.com?subject=xxx
A description for this approach can be found here (scroll down to the third option).

How can I populate the New E-mail Window (Subject and Body fields) using a Userform in MS Outlook?

I regularly issue Purchase Orders to vendors for my job, and either;
Write the email like a normal person or;
Use a macro to open a template that I have generated
Sub New_Email_from_PO_Template()
Dim myOlApp As Outlook.Application
Dim MyItem As Outlook.MailItem
Set myOlApp = CreateObject("Outlook.Application")
Set MyItem = myOlApp.CreateItemFromTemplate("C:\Blah\template.oft")
MyItem.Display
End Sub
My aim is to eliminate the possibility of error by creating a userform, which will then populate a New E-mail window, allowing me to make any desired changes, and add attachments, before manually clicking [Send].
Included here is a Userform I have created.
The textboxes in the Userform that I have created are as follows;
RecipientName
PurchaseOrderNumber
PurchaseOrderDescription
Location
ProjectNumber
DateRequired
Following [SubmitButton], the data would then be populated into the Subject and Body fields in the New E-mail window.
Subject Line:
"PO# [PurchaseOrderNumber] - [PurchaseOrderDescription] - [Location]"
Body:
"To [Recipient_Name],
Please find attached Purchase Order (PO# [PurchaseOrderNumber]) pertaining to [PurchaseOrderDescription] for [Location]. Date Required: [DateRequired]
Thanks and Kind Regards, [User's Outlook Signature]"
The code I have developed is below;
Sub ShowPOSubmissionUserform()
POSubmissionEmailGenerator.Show
End Sub
Sub InitialisePOSubmissionUserform()
'Empty ProjectNumberTextbox
ProjectNumberTextbox.Value = ""
'Empty ProjectNameTextbox
ProjectNameTextbox.Value = ""
'Empty PONumberTextbox
PONumberTextbox.Value = ""
'Empty RecipientNameTextbox
RecipientNameTextbox.Value = ""
'Empty DateRequiredTextbox
DateRequiredTextbox.Value = ""
End Sub
Private Sub CloseButton_Click()
Unload Me
End Sub
Private Sub SubmitButton_Click()
'Creates a new e-mail item and modifies its properties
Dim OutlookApp As Object
Dim MItem As Object
Dim email_ As String
Dim subject_ As String
Dim body_ As String
Dim attach_ As String
Set OutlookApp = CreateObject("Outlook.Application")
email_ = POSubmissionEmailGenerator.ProjectNumberTextbox.Value
subject_ = "Hello this is the subject"
body_ = "Line 1" & vbNewLine & vbNewLine & "Line 3"
'create Mail Item and send it
Set MItem = OutlookApp.CreateItem(0)
With MItem
.To = email_
.Subject = subject_
.Body = body_
End With
End Sub
At the moment, when pressing submit, NOTHING happens.
What needs to be added to make it at least open the New E-mail window?
With MItem
.To = email_
.Subject = subject_
.Body = body_
.Display '<<
End With

Run my Macro when excel cell changes

I am looking to have my spreadsheet send emails once a cell changes.
Thus far I have a macro to send to a group of emails and a command button macro to trigger this, but would like it to happen automatically when a cell changes state.
Now I have:
Sub Create_Email_From_Excel()
Dim SendTo As String
Dim ToMSg As String
For i = 1 To 10
SendTo = ThisWorkbook.Sheets(1).Cells(i, 1)
If SendTo <> “” Then
ToMSg = ThisWorkbook.Sheets(1).Cells(i, 3)
Send_Mail_From_Excel SendTo, ToMSg
End If
Next i
End Sub
Sub Send_Mail_From_Excel(SendTo As String, ToMSg As String)
Dim OutlookApp As Object
Dim OutlookMail As Object
Set OutlookApp = CreateObject("Outlook.Application")
Set OutlookMail = OutlookApp.CreateItem(0)
With OutlookMail
.To = SendTo
.CC = "john#interwebs.com"
.BCC = “”
.Subject = "You have mail"
.Body = "this is your mail"
.Send
End With
And...
Private Sub CommandButton1_Click
Create_Email_From_Excel
End Sub
I'm not sure where to go from here or if I'm going in the right direction. The command button and macros work but I am at a loss to go any further.
If it could excecute the create email from excel macro when a cell in column G changes from "pending" to "Late" that would be outstanding.
Try Worksheet_Change event
Example
Private Sub Worksheet_Change(ByVal Target As Range)
If Target.Address = "$G$1" Then
'
'When someone Edits the cell G1
'
Call Create_Email_From_Excel
'
'
End If
End Sub

How to add a Signature on Excel

I have an Excel spreadsheet Auditing Vendor documentation with expiry dates.
I have created an VBA macro which when I choose (Ctrl + M) will send an email requesting updates for specific documents based on the expiry dates.
Everything is beautiful and works like a charm.
My question is how do I include an Outlook Signature at the end of the email?
I would like it to pick up based on whoever has the spreadsheet open so that if Charlie Brown wants to trigger an email it would include Charlie Brown's Signature at the end.
It already auto-fills Charlie Brown as the Sender so I should be able to do this.
Any suggestions?
Here is an Example
Option Explicit
Sub AddSignature()
Dim olApp As Object
Dim olMail As Object
Set olApp = CreateObject("Outlook.Application")
Set olMail = olApp.CreateItem(0)
With olMail
.Display olMail.HTMLbody '<- adding default signature
End With
With olMail
.To = ""
.CC = ""
.BCC = ""
.Subject = ""
.HTMLbody = "Hello." & "<br>" & .HTMLbody '<- adding default signature
.Display
' .Send
End With
Set olMail = Nothing
Set olApp = Nothing
End Sub
also see Insert Signature in mail From Ron de Bruin
If you use excel to grab the new mail item signature you will get a flag for suspicious activity that the user could acknowledge
Dim OApp, OMail As Object
Set OApp = CreateObject("Outlook.Application")
Set OMail = OApp.CreateItem(0)
Dim sig As String
sig = OMail.HTMLbody
If you know the name of the signature you can go browse for it
Dir (CStr(Environ$("userprofile")) & "\appdata\roaming\microsoft\signatures\")