VBA Code to Send Emails From Excel
In VBA, to send emails from Excel, we can automatically automate our mailing feature to send emails to multiple users at a time. However, to do so, we need to remember that we may do it by outlook, another product of outlook, so we need to enable outlook scripting in VBA. Once done, we use the .Application method to use outlook features.
VBA’s versatility is just amazing. VBA coders love Excel because by using VBA, we not only can work within Excel. Rather, we can also access other Microsoft tools. For example, we can access PowerPoint, Word, and Outlook by using VBAMicrosoft Outlook has a VBA reference that can be used to control Outlook. This makes it easy to automate repetitive activities in Outlook. To use VBA in Outlook, you’ll need to enable the developer feature, just like in Excel.read more. So I was impressed when I heard of sending emails from Excel. Yes, it is true. We can send emails from excel. This article will show you how to send emails from Excel with attachments using VBA CodingVBA code refers to a set of instructions written by the user in the Visual Basic Applications programming language on a Visual Basic Editor (VBE) to perform a specific task.read more.
Table of contents
- VBA Code to Send Emails From Excel
- Set Reference to Microsoft Office Library
- 13 Easy Steps to Send Emails from Excel
- Step #1
- Step #2
- Step #3
- Step #4
- Step #5
- Step #6
- Step #7
- Step #8
- Step #9
- Step #10
- Step #11
- Step #12
- Step #13
- Recommended Articles
You are free to use this image on your website, templates, etc, Please provide us with an attribution linkArticle Link to be Hyperlinked
For eg:
Source: VBA Send Email from Excel (wallstreetmojo.com)
Set Reference to Microsoft Office Library
We need to send emails from Outlook. Since Outlook is an external objec, we first need object reference to “Microsoft Outlook 16.0 Object Library.”
- 1. In VBA, Go to Tools > References.
- Now, we will see the object reference library. In this window, we need to set the reference to “Microsoft Outlook 16.0 Object Library.”
- After setting the object reference, click on “OK.”
Now, we can access Outlook objects in VBA coding.
13 Easy Steps to Send Emails from Excel
Writing the code to send an email with an attachment from Excel is quite complicated but worth spending some time.
You can download this VBA Send Email Excel Template here – VBA Send Email Excel Template
Follow the below steps to write your first email excel macroA macro in excel is a series of instructions in the form of code that helps automate manual tasks, thereby saving time. Excel executes those instructions in a step-by-step manner on the given data. For example, it can be used to automate repetitive tasks such as summation, cell formatting, information copying, etc. thereby rapidly replacing repetitious operations with a few clicks.
read more.
Step #1
Start the sub procedure in VBASUB in VBA is a procedure which contains all the code which automatically gives the statement of end sub and the middle portion is used for coding. Sub statement can be both public and private and the name of the subprocedure is mandatory in VBA.read more.
Code:
Sub SendEmail_Example1() End Sub
Step #2
Declare the variable Outlook.Application
Code:
Dim EmailApp As Outlook.Application 'To refer to outlook application
Step #3
The above variable is an object variable. Therefore, we need to create an instance of a new object separately. Below is the code to create a new instance of the external object.
Code:
Set EmailApp = New Outlook.Application 'To launch outlook application
Step #4
Now, to write the email, we declare one more variable as “Outlook.MailItem”.
Code:
Dim EmailItem As Outlook.MailItem 'To refer new outlook email
Step #5
To launch a new email, we need to set the reference to our previous variable as “CreateItem.”
Code:
Set EmailItem = EmailApp.CreateItem(olMailItem) 'To launch new outlook email
Now, the variable “EmailApp” will launch outlook. In the variable “EmailItem,” we can start writing the email.
Step #6
We need to be aware of our items while writing an email. First, we need to decide to whom we are sending the email. So for this, we need to access the “TO” property.
Step #7
Enter the email ID of the receiver in double quotes.
Code:
EmailItem.To = "[email protected]"
Step #8
After addressing the main receiver, if you would like to CC anyone in the email, we can use the “CC” property.
Code:
EmailItem.CC = "[email protected]"
Step #9
After the CC, we can set the BCC email ID as well.
Code:
EmailItem.BCC = "[email protected]"
Step #10
We need to include the subject of the email we are sending.
Code:
EmailItem.Subject = "Test Email From Excel VBA"
Step #11
We need to write the email body using HTML body type.
Code:
EmailItem.HTMLBody = "Hi," & vbNewLine & vbNewLine & "This is my first email from Excel" & _
vbNewLine & vbNewLine & _
"Regards," & vbNewLine & _
"VBA Coder" 'VbNewLine is the VBA Constant to insert a new line
Step #12
We are working on if we want to add an attachment to the current workbook. Then, we need to use the attachments property. First, declare a variable source as a string.
Code:
Dim Source As String
Then in this variable, write ThisWorkbook.FullName after Email body.
Code:
Source = ThisWorkbook.FullName
In this VBA Code, ThisWorkbook is used for the current workbook and .FullName is used to get the full name of the worksheet.
Then, write the following code to attach the file.
Code:
EmailItem.Attachments.Add Source
Step #13
Finally, we need to send the email to the mentioned email IDs. We can do this by using the “Send” method.
Code:
EmailItem.Send
We have completed the coding part.
Code:
Sub SendEmail_Example1() Dim EmailApp As Outlook.Application Dim Source As String Set EmailApp = New Outlook.Application Dim EmailItem As Outlook.MailItem Set EmailItem = EmailApp.CreateItem(olMailItem) EmailItem.To = "[email protected]" EmailItem.CC = "[email protected]" EmailItem.BCC = "[email protected]" EmailItem.Subject = "Test Email From Excel VBA" EmailItem.HTMLBody = "Hi," & vbNewLine & vbNewLine & "This is my first email from Excel" & _ vbNewLine & vbNewLine & _ "Regards," & vbNewLine & _ "VBA Coder" Source = ThisWorkbook.FullName EmailItem.Attachments.Add Source EmailItem.Send End Sub
Run the above code. It will send the email with the mentioned body with the current workbook as the attachment.
Recommended Articles
This article has been a guide to VBA Send Email from Excel. Here, we learn how to write VBA code to send emails from Excel with attachments along with an example and downloadable Excel template. You can learn more about VBA from the following articles: –
- VBA TimeValue Function
- Dictionary in VBA
- Create Progress Bar in VBA
- GetOpenFilename VBA
Excel позволяет создавать диаграммы высокого качества, работать с огромным количеством данных, обрабатывать картинки, блок-схемы и многое другое. И даже если вам и этого не достаточно, можно использовать Excel для автоматической отправки писем с помощью встроенного VBA редактора.
Данная статья описывает три способа отправки писем с помощью VBA в Excel. Вы можете скачать файл с примером отправки email с помощью VBA в Excel.
Отправить письмо в Excel с помощью VBA
Один из самых простых способов для автоматизации отправки почты с Excel заключается в вызове функции Create («ObjectOutlook.Application»). Данная функция возвращающает ссылку на ActiveX объект (в данном случает приложение Outlook), которое затем используется для создания и отправки электронной почты.
Чтобы проверить данный способ в работе, скопируйте и вставьте код ниже в VB редактор.
1 |
Sub Send_Email_Using_VBA() |
В качестве напоминания: Когда вы пытаетесь отправить письмо вышеуказанным способом, система безопасности будет выдавать каждый раз предупреждающее окно, в котором будет говориться о том, что Программа пытается отправить сообщение от вашего имени… и возможности обойти этот шаг нет.
К счастью, существует еще два способа, с помощью которых данный вопрос может быть решен: первый – через использование CDO, второй – имитирующий использование событий нажатий клавиш клавиатуры.
Отправить письмо в Excel с помощью CDO
Что такое CDO? CDO является библиотекой объектов, которая предоставляет интерфейс Messaging Application Programming Interface (MAPI). CDO позволяет манипулировать обменом данных, и отправлять и получать сообщения.
Использование CDO может быть предпочтительно в случаях, когда вы хотите предотвратить появление вплывающих окон безопасности Программа пытается отправить сообщение от вашего имени… и следовательно, предотвратить задержку отправки сообщения.
В нашем примере мы используем функцию CreateObject («CDO.Message»). Важно отметить, что необходимо правильно установить конфигурацию SMTP сервера, чтобы не допустить появления ошибок Run-time error 2147220973(80040213) или sendUsing configuration value is invalid. Пример ниже настроен на отправку сообщений через почту Google (Gmail). Для других почтовых серверов, вам потребуется ввести свои значения SMTP-сервера и SMTP-порта.
1 |
Sub CDO_Mail_Small_Text_2() |
Обратите внимание, чтобы воспользоваться данным методом вам необходимо подключить библиотеку CDO в редакторе макросов Tool –> References.
Отправить письмо в Excel с помощью Send Keys
Другой способ отправки email с помощью Excel – использование команды ShellExecute, которая выполняет любую программу в VBA. Команда ShellExecute используется для загрузки документа с соответствующей программой. По сути, вы создаете объект String (текстовые данные) и передаете его в качестве параметра для функции ShellExecute. Остальная часть операций выполняется в окнах. Автоматически определяется, какая программа связана с данным типом документа и используется для загрузки документа. Вы можете использовать функцию ShellExecute, чтобы открыть Internet Explorer, Word, Paint и множество других приложений. В коде ниже используется задержка в три секунды, чтобы убедиться, что отправляемое письмо корректно и для возможности предотвратить отправку, если вы вдруг нашли какие-нибудь недочеты.
1 |
Sub Send_Email_Using_Keys() |
Cкачать файл с примером отправки email с помощью VBA в Excel
VBA Send Email From Excel
VBA is not only limited to data in excel. We can send emails through VBA and this is what we will learn in this article. It requires considerable knowledge of VBA and its methods to write the code to send emails from excel. Before we move to write and sending emails from excel let us know what this automation means. This type of automation means accessing a feature of another application using any other application. Now the mailing feature is offered by Microsoft in Outlook, we will use methods and properties of outlook in excel to send emails. To send an email we need to know the basic of email also. In layman’s term, what is the process and what is the requirement to send an email? An Email consists of an email address of the sender if there is a CC (Carbon Copy ) or a BCC and a subject line with an email body.
How to Send Emails From Excel VBA?
Let us learn how to send emails through outlook from excel in VBA by an example. In this example, we will also send an attachment to the receiver, the same excel file we will be writing the code.
You can download this VBA Send Email Excel Template here – VBA Send Email Excel Template
Follow the below steps to send email from Excel Using VBA code:
Step 1: In the Developer Tab click on Visual Basic to open the VB Editor.
Before we move into writing codes to send an email, we need to know this that outlook is an external object and we need to refer it in the VBA.
Step 2: Go to Tools and then select References.
Step 3: Clicking on the reference will open a wizard box for us, find a reference for Microsoft Outlook Object library and check it and then click on Ok.
Step 4: Click on insert tab and insert a module in the VBA project.
Step 5: Define a subprocedure as shown below.
Code:
Sub EmailExample() End Sub
Step 6: By giving reference to the outlook above, we can now access the properties of outlook in VBA. Now let us declare a variable as an outlook application.
Code:
Dim Email As Outlook.Application
Step 7: Like FSO, this variable is an object variable, so to access any other application we need to create some instances, create an instance as shown below using the SET keyword.
Code:
Set Email = New Outlook.Application
Step 8: Since we want to send an attachment to the receiver we need to declare one variable as String which will hold the path for the attachment.
Code:
Dim Sr As String
Step 9: Now let us start with the mailing part in this code, to send an email we need to define another variable which will use the property of outlook to refer to a new email as shown below.
Code:
Dim newmail As Outlook.MailItem
Step 10: Similar to above with using another application in the example we need to create instances, now we need to create an instance for a new email which will open the new email using the set keyword.
Code:
Set newmail = Email.CreateItem(olMailItem)
Before we move further let me explain our progress so far, the first instance will open outlook for us while the second instance will open the new email for us.
Step 11: As I have explained above about what is the requirement to send an email. The first requirement is a receiver which is “To” in an email. So let us use the To property of outlook in excel as follows.
Code:
newmail.To = "[email protected]"
Step 12: Since we have used the To property we have some another feature to use such as the Carbon Copy or the CC property of outlook.
Code:
newmail.CC = "[email protected]"
Similarly, we can use the BCC property.
Note: BCC property is used when we want to hide the email address of the BCC receiver from the other receivers.
What is the next step in sending an email?
Step 13: It is subject. When we write the instance name with a dot operator we can see the option for a subject as follows.
Step 14: Press Tab on the subject IntelliSense and write a random subject as shown below.
Code:
newmail.Subject = "This is an automated Email"
Step 15: The next step in writing an email is a body for the email. Like the properties, we used above with the instance let us use the body property of the outlook to write the body as follows.
Code:
newmail.HTMLBody = "Hi," & vbNewLine & vbNewLine & "This is a test email from Excel" & _ vbNewLine & vbNewLine & _ "Regards," & vbNewLine & _ "VBA Coder"
Step 16: Now we have created an email with a body and subject line in it. The next step is to add an attachment to the email. Since we want to send the current worksheet to the receiver we will use the path as follows,
Code:
Sr = ThisWorkbook.FullName
Step 17: Now we can send the attachment using the attachment property as shown below.
Code:
newmail.Attachments.Add Sr
Step 18: Now finally we need to send the email. Like in outlook we press the send button to send an email, similarly, we will use the send properties of outlook as follows.
Code:
newmail.Send
Final Full code
So below is the final code on how to send an email from Excel with the help of VBA.
Code:
Sub EmailExample() Dim Email As Outlook.Application Set Email = New Outlook.Application Dim Sr As String Dim newmail As Outlook.MailItem Set newmail = Email.CreateItem(olMailItem) newmail.To = "[email protected]" newmail.CC = "[email protected]" newmail.Subject = "This is an automated Email" newmail.HTMLBody = "Hi," & vbNewLine & vbNewLine & "This is a test email from Excel" & _ vbNewLine & vbNewLine & _ "Regards," & vbNewLine & _ "VBA Coder" Sr = ThisWorkbook.FullName newmail.Attachments.Add Sr newmail.Send End Sub
When we run the above code we need to wait for a few seconds for the code to execute and we can check out sent box in outlook that the email has been sent through excel.
Things to Remember
- We use another application to send an email from excel.
- To use another application we create instances.
- Before using outlook as another application we need to refer to Outlook objects from the reference tab.
- We need to know the requirements of an email to send an email.
Recommended Articles
This is a guide to VBA Send Email From Excel. Here we discuss how to send emails with attachments from excel using VBA code along with an example and downloadable excel template. Below are some useful excel articles related to VBA –
- VBA Hyperlink
- VBA Outlook
- VBA Get Cell Value
- VBA Web Scraping
To send emails from Microsoft Excel only requires a few simple scripts. Add this functionality to your spreadsheets, and you can accomplish much more in Excel.
Excel macros can do many of the same things VBA scripts can, without the need for as much programming knowledge. VBA lets you implement more advanced routines, like creating a spreadsheet report with all of your PC information.
Prefer to watch this tutorial as a video? We’ve got you covered!
Why Send Email From Excel?
There are a lot of reasons why you might want to send an email from inside Microsoft Excel.
Maybe you have staff who update documents or spreadsheets every week, and you’d like to receive an email notification when they do. Or you might have a spreadsheet of contacts, and you want to send one email to all of them at once.
You’re probably thinking that scripting an email broadcast from Excel is going to be complicated. That’s not the case at all. The technique in this article makes use of a feature that’s been available in Excel VBA for a long time, Collaboration Data Objects (CDO).
CDO is a messaging component used in Windows since very early generations of the OS. It used to be called CDONTS, and then with the advent of Windows 2000 and XP, was replaced with «CDO for Windows 2000.» This component is already included in your VBA installation within Microsoft Word or Excel and is ready for use.
Using the component makes sending emails from within Windows products with VBA extremely easy. In this example, you’ll use the CDO component in Excel to send out an email that will deliver the results from a specific Excel cell.
Step 1: Prepare Your Gmail Account
To send email from Microsoft Excel, we’ll be using Gmail, though you can customize the macro below to work with other email clients. Note that Gmail no longer permits third-party app access, meaning you’ll first have to enable Gmail’s 2-step authentication.
From your Google account’s Security page, under Signing in to Google, click App passwords. On the App passwords screen, find the Select app drop-down menu and select Mail. From Select device, select Windows Computer. Then click GENERATE.
Jot down the 16-character app password; you’ll need it when you configure the macro.
Step 2: Create a VBA Macro
Tip: Before you start, save the Excel file you’ll be working with as a Macro-Enabled Workbook, i.e. in the XLSM format.
First, we’ll need the Excel Developer tab. If you don’t see it, here’s how to enable it:
- Go to File > Options.
- Under Customize the Ribbon > Main Tabs, check the Developer option.
- Click OK to save your changes.
Inside Excel’s Developer tab, click on Insert in the Controls box, and then select a command button.
Draw it into the sheet and then create a new macro for it by clicking on Macros in the Developer ribbon.
When you click the Create button, it’ll open the VBA editor.
Add the reference to the CDO library by navigating to Tools > References in the editor.
Scroll down the list until you find Microsoft CDO for Windows 2000 Library. Mark the checkbox and click OK.
When you click OK, make note of the name of the function where you’re pasting the script. You’ll need it later.
Step 3: Configure Your Macro
Now you’re ready to create the mail objects and set up all the fields necessary to send an email. Keep in mind that while many of the fields are optional, the From and To fields are required. Paste all the code snippets below into your Module1 (Code) window.
This is what the complete code looks like:
Sub Send_Emails()
Dim NewMail As CDO.Message
Dim mailConfig As CDO.Configuration
Dim fields As Variant
Dim msConfigURL As String
On Error GoTo Err: 'early binding
Set NewMail = New CDO.Message
Set mailConfig = New CDO.Configuration
'load all default configurations
mailConfig.Load -1
Set fields = mailConfig.fields
'Set All Email Properties
With NewMail
.From = "username@gmail.com"
.To = "username@gmail.com"
.CC = ""
.BCC = ""
.Subject = "Send Email From an Excel Spreadsheet"
.TextBody = "This is the body of your email. And here is some added data:" & Str(Sheet1.Cells(2, 1))
.Addattachment "c:dataemail.xlsx" 'Optional file attachment; remove if not needed.
.Addattachment "c:dataemail.pdf" 'Duplicate the line for a second attachment.
End With
msConfigURL = "http://schemas.microsoft.com/cdo/configuration"
With fields
.Item(msConfigURL & "/smtpusessl") = True 'Enable SSL Authentication
.Item(msConfigURL & "/smtpauthenticate") = 1 'SMTP authentication Enabled
.Item(msConfigURL & "/smtpserver") = "smtp.gmail.com" 'Set the SMTP server details
.Item(msConfigURL & "/smtpserverport") = 465 'Set the SMTP port Details
.Item(msConfigURL & "/sendusing") = 2 'Send using default setting
.Item(msConfigURL & "/sendusername") = "username@gmail.com" 'Your gmail address
.Item(msConfigURL & "/sendpassword") = "password" 'Your password or App Password
.Update 'Update the configuration fields
End With
NewMail.Configuration = mailConfig
NewMail.Send
MsgBox "Your email has been sent", vbInformation
Exit_Err:
'Release object memory
Set NewMail = Nothing
Set mailConfig = Nothing
End
Err:
Select Case Err.Number
Case -2147220973 'Could be because of Internet Connection
MsgBox "Check your internet connection." & vbNewLine & Err.Number & ": " & Err.Description
Case -2147220975 'Incorrect credentials User ID or password
MsgBox "Check your login credentials and try again." & vbNewLine & Err.Number & ": " & Err.Description
Case Else 'Report other errors
MsgBox "Error encountered while sending email." & vbNewLine & Err.Number & ": " & Err.Description
End Select
Resume Exit_Err
End Sub
And these are the sections and fields you need to customize:
- With NewMail: This section contains all the parameters for sending your email, including the body of your email. The .From field needs to contain your Gmail address, but you’re free to set the other fields however you want. For the body, you can piece together components of the message by using the & string to insert data from any of the Microsoft Excel sheets right into the email message, just like shown above. You can also attach one or more files.
- With fields: This is where you configure your SMTP settings for your Gmail account. Leave the smtpserver and smtpserverport fields as is when copying the code. Enter your Gmail username and the 16-digit app password into the respective fields.
Step 4: Test Your Macro
In the VBA editor, go to Run > Run Sub/User Form or press F5 to test the macro. If your email fails to go through, you should see an error message. Otherwise, you’ll see a confirmation that your email was sent successfully.
If you receive an error that reads The transport failed to connect to the server, make sure you’ve entered the correct username, password, SMTP server, and port number in the lines of code listed underneath With fields.
Step 5: Connect the Command Button to Your Script
To connect your command button to this script, go into the code editor and double-click on Sheet1 to view the VBA code for that worksheet. Select your button, e.g. CommandButton1, from the drop-down on the left and define the action on the right; Click works. Then type the name of the function where you pasted the script above; in our example it’s Send_Emails.
When you go back to your sheet now, click the button to send the email.
Here’s an example of what the message should look like in your inbox:
Take It Further and Automate the Whole Process
It’s all well and good to be able to send email from Excel at the touch of a button. However, you might want to use this functionality regularly, in which case it makes sense to automate the process. To do so, you’ll need to make a change to the macro. Head to the Visual Basic Editor and copy and paste the entirety of the code you’ve put together so far.
Next, double-click ThisWorkbook from the VBAProject hierarchy.
From the two dropdown fields at the top of the code window, select Workbook and select Open from the Methods dropdown.
Paste the email script above into Sub Workbook_Open().
This will run the macro whenever you open up the Excel file.
Next, open up Task Scheduler. You’re going to use this tool to ask Windows to open up the spreadsheet automatically at regular intervals, at which point your macro will run, sending the email.
From the Action menu, select Create Basic Task… and work your way through the wizard until you reach the Action screen.
Select Start a program and click Next. Use the Browse button to find Microsoft Excel’s location on your computer, or copy and paste the path into the Program/script field. Then, enter the path to your Microsoft Excel document into the Add arguments field. Complete the wizard, and your scheduling will be in place.
It’s worth running a test by scheduling the action for a couple of minutes in the future, then amending the task once you can confirm that it’s working.
Note: You may have to adjust your Trust Center settings to ensure that the macro runs properly.
To do so, open the spreadsheet and navigate to File > Options > Trust Center. From here, click Trust Center Settings…, and on the next screen set the radio dial to Never show information about blocked content.
Make Microsoft Excel Work for You
Microsoft Excel is an incredibly powerful tool, but learning how to get the most out of it can be a little intimidating. If you want to truly master the software, you’ll need to be comfortable with VBA, and that’s no small task.
However, the results speak for themselves. With a little VBA experience under your belt, you’ll soon be able to make Microsoft Excel perform basic tasks automatically, giving you more time to concentrate on more pressing matters.
Return to VBA Code Examples
This tutorial will show you how to send emails from Excel through Outlook using VBA.
Sending the Active Workbook
Function SendActiveWorkbook(strTo As String, strSubject As String, Optional strCC As String, Optional strBody As String) As Boolean
On Error Resume Next
Dim appOutlook As Object
Dim mItem As Object
'create a new instance of Outlook
Set appOutlook = CreateObject("Outlook.Application")
Set mItem = appOutlook .CreateItem(0)
With mItem
.To = strTo
.CC = ""
.Subject = strSubject
.Body = strBody
.Attachments.Add ActiveWorkbook.FullName
'use send to send immediately or display to show on the screen
.Display 'or .Send
End With
'clean up objects
Set mItem = Nothing
Set appOutlook = Nothing
End Function
The function above can be called using the procedure below
Sub SendMail()
Dim strTo As String
Dim strSubject As String
Dim strBody As String
'populate variables
strTo = "jon.smith@gmail.com"
strSubject = "Please find finance file attached"
strBody = "some text goes here for the body of the email"
'call the function to send the email
If SendActiveWorkbook(strTo, strSubject, , strBody) = true then
Msgbox "Email creation Success"
Else
Msgbox "Email creation failed!"
End if
End Sub
Using Early Binding to refer to the Outlook Object Library
The code above uses Late Binding to refer to the Outlook Object. You can add a reference to Excel VBA, and declare the Outlook application and Outlook Mail Item using Early Binding if preferred. Early Binding makes the code run faster, but limits you as the user would need to have the same version of Microsoft Office on their PC.
Click on the Tools menu and References to show the reference dialog box.
Add a reference to the Microsoft Outlook Object Library for the version of Office that you are using.
You can then amend your code to use these references directly.
A great advantage of early binding is the drop down lists that show you the objects that are available to use!
Sending a Single Sheet from the Active Workbook
To send a single sheet, you first need to create a new workbook from the existing workbook with just that sheet in it, and then send that sheet.
Function SendActiveWorksheet(strTo As String, strSubject As String, Optional strCC As String, Optional strBody As String) As Boolean
On Error GoTo eh
'declare variables to hold the objects required
Dim wbDestination As Workbook
Dim strDestName As String
Dim wbSource As Workbook
Dim wsSource As Worksheet
Dim OutApp As Object
Dim OutMail As Object
Dim strTempName As String
Dim strTempPath As String
'first create destination workbook
Set wbDestination = Workbooks.Add
strDestName = wbDestination.Name
'set the source workbook and sheet
Set wbSource = ActiveWorkbook
Set wsSource = wbSource.ActiveSheet
'copy the activesheet to the new workbook
wsSource.Copy After:=Workbooks(strDestName).Sheets(1)
'save with a temp name
strTempPath = Environ$("temp") & ""
strTempName = "List obtained from " & wbSource.Name & ".xlsx"
With wbDestination
.SaveAs strTempPath & strTempName
'now email the destination workbook
Set OutApp = CreateObject("Outlook.Application")
Set OutMail = OutApp.CreateItem(0)
With OutMail
.To = strTo
.Subject = strSubject
.Body = strBody
.Attachments.Add wbDestination.FullName
'use send to send immediately or display to show on the screen
.Display 'or .Display
End With
.Close False
End With
'delete temp workbook that you have attached to your mail
Kill strTempPath & strTempName
'clean up the objects to release the memory
Set wbDestination = Nothing
Set wbSource = Nothing
Set wsSource = Nothing
Set OutMail = Nothing
Set OutApp = Nothing
Exit Function
eh:
MsgBox Err.Description
End Function
and to run this function, we can create the following procedure
Sub SendSheetMail()
Dim strTo As String
Dim strSubject As String
Dim strBody As String
strTo = "jon.smith@gmail.com"
strSubject = "Please find finance file attached"
strBody = "some text goes here for the body of the email"
If SendActiveWorksheet(strTo, strSubject, , strBody) = True Then
MsgBox "Email creation Success"
Else
MsgBox "Email creation failed!"
End If
End Sub
VBA Coding Made Easy
Stop searching for VBA code online. Learn more about AutoMacro — A VBA Code Builder that allows beginners to code procedures from scratch with minimal coding knowledge and with many time-saving features for all users!
Learn More!