Discover the Anyleads suite | Find emails, verify emails, install a chatbot, grow your business and more!.
blog

How do I get Excel to automatically send emails?



How do I get Excel to automatically send emails?


You can use macros with Office products like Word or PowerPoint, but how about sending out automatic messages from Excel itself? Well, there are ways! We'll show you three different methods for automating your daily spreadsheet tasks so that they happen without any interaction on your part at all—automate away.

We're going to take advantage of VBA (Visual Basic for Applications) programming language to achieve this automation, which means we need to have some coding knowledge. If not, don't worry too much because it's easy enough to learn VB if you follow along step-by-step. You may also want to check out our beginner’s guide to Microsoft Access first before continuing.

Can I get a macro in Excel to send emails?

Yes, you can. But maybe not quite as simple as just clicking a button. In order to be able to send emails through Excel, you will need to make sure two things: 1.) Have access to Exchange server 2.) The ability to add ActiveX controls to your worksheet. This is what allows us to use the "application" object.

ActiveX control is basically another way of saying “object” in terms of coding. It refers to one particular function within a program. For example, if you open up Notepad and type in "Hello World," then save the file, you would technically say it has its own unique identifier called an Object ID. When you write code by typing commands into Visual Basic, you must tell the computer what kind of object you want to call upon. An Application object tells Excel specifically what command you'd like to run. Once you've got everything set up correctly, you can build your script and execute it.

Now let's move onto building your script. First, go ahead and download the sample code below named MacroTestVBEProject.zip. Extract where ever you extracted the files to (in my case C:\Users\Owner\Desktop). Then right click anywhere on your desktop and select New & Other… Make sure to pick Windows Script File (.wsf), name whatever you want, and hit OK. That should install something similar to this.

Next, copy and paste the following code inside the.wsf file. Save changes when prompted.

This is the basic skeleton of anything written in VBA. Your project needs to contain several objects such as buttons, textboxes, etc., but we won't concern ourselves with those today. Instead, we will focus solely on the Application object. To start off, lets declare variables that will store information related to each specific action. These include names, addresses, phone numbers, subject lines, message bodies, etc. Next, we will define functions that accomplish these actions. Functions allow users to input certain instructions and perform them over and over again until modified elsewhere.

After declaring the variable needed, we begin creating functions. A function consists of more than one line of code enclosed between brackets [ ] ("[Function Name]"). Here is an example of creating a function named DisplayMessage(). Inside the parentheses, display text boxes labeled txtName and txtEmail. Output their contents to the screen via MessageBox() method. At the end, clear the contents of both boxes with ClearContents(), making room for new inputs. Finally, close off the function with End Function". After doing so, press F5 to launch the application. Enter your desired values next to txtFirstname, txtLastname, txtPhoneNumber1, txtSubjectLine, txtBodyText, and txtSendButton. Click Send Email once finished. Note that depending on your settings, you might receive security warnings regarding unsigned applications. Simply choose Yes to proceed.

Once complete, try modifying the number fields to see the effects change instantly. Now try changing the body text in the same field as well. Notice how the output remains the same even though the content was changed? That's how functions work.

Below is the completed script after taking out unnecessary bits.

Sub Main()Dim strTo As String Dim intStartTime As Integer Dim intEndtime As Integer Dim objMailApp As Mail_Application Dim iMsg As MSG Dim lngCount As Long Dim xlWB As Workbooks Dim xlSheet As Worksheet Dim strFilePath As String On Error Resume Next Set xlWB = GetObject( _ '"Excel.Workbook' ) With xlWB.Worksheets("MySpreadsheet") Do While True Loop While Sheets("Control Panel").AutoFilterMode = False And Len(strTo) > 0 Continue DoEvents Until DateDiff("d", Timer, Now()) ""Timer""=intStart Time Cells(2, 3) = Now() intEndtime = Range("A8").Value Exit Sub MsgBox ("Sent mail successfully.") Else Msgbox ("Error while trying to send mail.") End If WScript.Quit intEndtime = Int((24 * 60 * 60)) + ((3600 Mod intEndtime)), -3600000) Debug.Print intEndtime Return End Sub

Try running the above code now and seeing if it does exactly what you wanted. Keep in mind that you can only reference cells whose value hasn't been altered since the time the user clicked the send button. Also note that we used the main subroutine instead of calling the function directly. Calling the function causes execution immediately whereas referencing the subroutine waits for it to finish looping.

So why bother having functions at all? Well, as mentioned earlier, functions allow you to repeat many actions over and over again easily. They are great for repetitive processes. Plus, they help keep your overall code organized and readable.

Can you automate emails from Excel?

If you recall, we had declared five variables in our function. Those were intended to hold various pieces of information pertaining to our automated process. However, it turns out that we never actually utilized those variables. Let's rewrite the function above slightly to incorporate those variables. Go ahead and extract the zip file wherever you put it (C:\User\Owner\Desktop). Open up the newly created.wsf file in a text editor and replace the existing code with this.

Option Explicit Private Declare Variables strRecipient As Variant dim oRc as outlook.recipients Dim sSender As String dim msoLanguageID As String dim varAttn As string dim varCC As String dim varBCC As String dim strReplyTo As variant dim smtpServer As Object dim nFormStyle as formstyle private Sub Form_Activate () Dim objOutlook As Object Dim rptTos As RecipientItems Dim fldTitle As MSformcontrol Dim chkExpires As MSformcontrol Dim blnIgnoreBlank As MSformcontrol Dim lngItemIndex As long Dim lngRowPosition As long Dim lngColWidth As single Dim intStartTime As integer Dim intEndtime As integer Dim strFrom As String Dim strFilePath As String Dim wbTarget As Workbook Dim shtSource As Sheet Dim strContent As String Dim vntCell As Variant Dim retVal As Variant Dim errNum As errorhandler Dim Rowspercolumn Dim Columnsperrow Dim colwidth Dim Rowposistion Dim Colwidth ''dim arraylist'' Retrieve recipients From ListRetrieveList ''Set smtpServer = CreateObject("CDO.CommandDispenser") ''set properties ''smtpServer.Transport Type = "http://schemas.microsoft.com/cdo/configuration/".Configuration = "http://schemas.microsoft.com/cdo/configuration/".Charset = "UTF-8".ClearHeaders = "from:" : Subject = "Dear "& shtSource.'tab': strFROM = shtSource."title": fldTITLE = "Please enter recipient details here."inputmask="true": tabindex=-1""" /" ""InputMask=""True"" /" InputValidator=""false"" """ "On Error Resume Next Selection.AddItem strRecipientForLoop : For Each vntCell In Split(shtSource.'items', Chr$(32): Next vntCell.Caption: If Err.number "" 438 Then selection.item(0).value = Left$(vntCell.Caption, InStrRev(vntCell.Caption, "$")) Else ''if no errors exit for loop Else ''display alert box with error msg else ''DisplayAlert ("There Were Some Errors Adding Data!", vntCell.Caption, "OK") end if Next: StopHere: rowPosistiton = 0 ''loop column positions: For Each vntCell In Split(shtSource.''colspecs', Chr$(32): For Each vntCell In Split(shtSource.''colspec', Chr$(34)): intColumn = InStr(vntCell,''/'') intColumn = Right$(vntCell, Length(vntCell)-intColumn+1) colwidth = LTrim$(vntCell,intColumn) intColumn = InStr(vntCell,''msoOffsetLabelTypeId='Table HdrOff'"') intColumn = Right$(vntCell,Length(vntCell)-intColumn+1) colwidth = LTrim$(

Excel is a powerful tool for creating spreadsheets filled with information, but it’s also useful as a standalone application that you can use directly on your desktop. One way to take advantage of this power is by automating tasks via macros or VBA code.  Macros allow users to perform repetitive actions without having to manually type them into cells every time they want to run those commands. And while there are many ways to create macros in Excel, one common example involves linking certain values within a spreadsheet to specific functions or instructions. This article will show how to accomplish both scenarios. In addition, we'll look at three different methods used to trigger automated messages through Excel scripts—and which ones might be most appropriate for each case.

First up, let's walk through the process of linking a value in Excel to an action. To do so, first open Microsoft Office 2013 and then select File " Options " Customize Ribbon. Select Main Tabs along the top ribbon row and scroll down until you see Manage Ribbon Commands. Click Edit next to Display Name under Categories. Then, click New Category to add a new entry. Enter “Email Links" (or whatever name works best) and hit OK. You should now see Email Link listed near the bottom of the list of categories.

Next, right-click anywhere inside any existing tab and select View Code. Now, copy and paste the following script into the code window at the top of Notepad or WordPad. When finished, save the file as xlsm (x64). Make sure to change the.XLSM extension if necessary. The below sample uses the ActiveCell object to determine what text string to assign to the function. It could just as easily have been set up using a static number instead of selecting a particular cell range. Finally, note that the line labeled Output refers to where you would like the user to end up after running the script. For our purposes here, this means sending an email.

Now when you return to your spreadsheet, you may notice something odd happening because a message box appears asking whether you really want to continue. That's normal. What you're doing is assigning a shortcut key combination to activate the above command. So long as you don't cancel out of said box, everything else will work normally. If you decide not to go forward with adding shortcuts to your system, simply delete that portion of the code.

If you’d rather not mess around with keyboard keys, the second method outlined in this guide allows users to execute a single button or menu item to initiate an entire series of events. Next, follow these steps to configure Excel to send automatic messages based on a defined event. Go back to the customizing section described earlier, choose Mailings Tools, and then Add Button. Create a new button called Send EMAIL and fill in all fields except CommandButton1_Click. Instead, enter CommandButton2_CommandButton. Hit OK.

Now, head back over to your main sheet tabs and select View Code again. Paste the following script below the placeholders already present. Notice that unlike the previous example, this version requires no InputBox prompts—only some basic logic involving determining whether the current date falls between two dates. Also, make sure to replace the hardcoded numbers in this script with variables representing actual month/day pairs. Save this as xlsb. Your final task before testing this functionality is to ensure that your computer has SMTP access enabled for outgoing mail. Open Control Panel " Administrative Tools and double-check Account Manager " Properties. Under Connection Tab, check Allow remote connections and Apply changes.

The last step required to complete the test is to enable the Macro Security feature. Right-click My Computer, point to Advanced System Settings, and select Environment Variables. Scroll down to Windows Script Host and double-click WshShell. Choose Shell. At the prompt, input wscript.exe shell\cScripts\macroSecurityTest.wsf /nologo. Press Y followed by A to accept the default confirmation dialog. Restart Excel. Once the restart completes, navigate to the toolbar icon dropdown located in the upper left corner of your screen. From here, select Macros " Browse All Files... and locate the newly created.xlb file containing your Send EMAIL routine. Double-click this file and press F5 to launch the macro. Note that if the program crashes during execution, you may need to disable the Visual Basic Editor setting Automatically detect XML errors in order to avoid crashing upon opening the document.

After launching the macro, you’ll receive a pop-up stating that the sender address was invalid. Simply close this alert and proceed to the next page. On the third page, you’ll see four lines of output indicating success. However, Excel won’t actually send anything unless you specify otherwise. As such, feel free to exit out of the automation once you've achieved desired results. Otherwise, keep navigating pages until you reach the fourth and final stage. Here, Excel will display another error message saying that it failed to transmit the specified items due to an internal connection failure. Again, simply close out of this notification. After relaunching the macro, you should now be able to view your completed script in its entirety. Congratulations! Since you’re already familiar with coding, it shouldn't take too much effort to tweak this script to fit your needs better.

For more detailed help on configuring your settings and accessing the scripting environment, refer to online resources provided by Microsoft. They include How to Set Up Remote Connections With XPComputers.mspxpcomputers.html and Accessing the Windows Script Host Using Shell.mspxpshell.html.

Finally, in response to the original question posed regarding triggering emails from Excel, the answer depends on what kind of software you plan to use to handle incoming correspondence. While there isn't a dedicated applet specifically designed to manage email correspondence, several options exist that integrate well with MS Office. Third party programs like Zoho Writer offer robust features like scheduling, tracking, templates, and more. Other services like Gmail, Yahoo!, Hotmail, and others provide similar capabilities. But regardless of your choice, keep in mind that you must have permission to send e-mails on behalf of other people.

In closing, Excel is capable of far more than merely managing spreadsheets. Users can leverage macros and VB programming techniques to develop sophisticated applications built entirely on this popular productivity suite. Of course, Excel offers ample support and documentation available from Microsoft itself. Therefore, anyone interested in learning about writing their own macros and integrating complex formulas into Excel workbooks should consult the official site and reference manual. Or perhaps you'd prefer to try implementing some of the ideas suggested in this piece. Either way, the sky truly is the limit!

Have questions or comments concerning this post? Feel free to leave feedback in the comments section below.

Excel is great for creating spreadsheets that tell stories or communicate information clearly, but it can also be used as a tool to automate repetitive tasks such as sending out automated reports or reminders. In this article we'll show you how easy it is to use macros within your spreadsheet to automatically send out email messages. We've even included three useful scenarios where you might want to take advantage of this functionality!

Automatically Sending Email From Cell Content in Excel

The first step toward automating any task with Excel involves setting up a macro. This allows us to perform actions on our sheet without having to manually type them into VBA code every time. To set up a macro in Excel 2007-2010 open Tools " Macros. You should see something similar to this screen when you click OK (the exact location will vary depending upon which version of Office you are running).

In Excel 2003 select Developer then Visual Basic Editor. The following steps apply to both versions.

Click New Document... or press Ctrl + N. A wizard window opens asking what kind of document you'd like to make. For now choose Macro Module because we're going to add some basic instructions later. Then hit Next.

Enter a Name for the project, select Microsoft Word 97 - 2010 if prompted, and continue until you reach Finish. Your new macro module appears under MyMacroName.xlsm. Double-click it right away so that Windows knows it exists.

Now let's start adding some code by selecting View Code.... Here we need to enter our script. Click anywhere in the text box and begin entering commands in VB (Visual Basic) language. Press F5 after each line to run through your code. If everything works correctly you'll see the message Run Workbook_Open() at the bottom left corner of the editor window. Now you know your code has been successfully recorded.

It may look daunting at first glance, but once you have written your first few lines you'll realize just how simple programming logic really is. It all comes down to logical statements that control various parts of your program. Let's break down the example below so that you understand exactly what's happening here.

This section tells Excel to launch Outlook whenever you double-click on a given range of cells in your spreadsheet. That way, you don't have to worry about opening a separate application to compose new mail messages. However, there are two things wrong with this approach: 1.) You must open Outlook before editing the contents of those cells, and 2.) You cannot insert variables into your statement. So next we'll fix these problems one at a time.

First, let's address problem number one:

We'll solve this problem simply by moving the command LaunchOutlook directly beneath the instruction that launches Outlook whenever the user clicks on another cell. Don't forget to include the semicolon between the end of the previous instruction and the beginning of the new one.

To deal with the second issue, let's change the name of the variable that stores the path to Outlook.exe. Right-click inside the Dim strPath$ declaration and select Rename Current Variable. Change its name to exeFilePath.

Next, replace the hardcoded string reference "C:\Program Files\Microsoft Office" in your existing code with the value stored in exeFilePath. Finally, copy the remainder of the original code above and paste it underneath the modified portion. Make sure you remove the old code entirely so you only have the new stuff. Once you've done that, save the file.

If everything looks good, close the.vbs file and try running the newly updated macro again. When you double-click on certain cells in your spreadsheet, the message Run Workbook_Open() appears, followed by Outlook being launched immediately. All of the other options presented during installation still appear unchanged in your dialogs, however -- this means that no matter whether you chose Always ask me what to do or Notify me when updates are available, the software won't prompt you to install updates. Also, note that since you changed the default directory for launching programs, you probably won't see Outlook listed among your choices unless you specify otherwise.

You can test out your macro by changing the values in the cells below:

Change the numbers to different figures.

Press Alt+S, H, O, U, B, C keys together.

Save the changes and exit.

Try clicking on the cells containing your new formulas.

Your spreadsheet should update itself automatically with the new calculations. As long as you saved the workbook beforehand, Excel should provide you with the option to Send Changes via eMail instead of bringing up the standard Save Data dialogue.



Can Excel send an email automatically?

Yes, Excel 2013 and newer can send individual emails based on conditions contained within your spreadsheet. All you need to do is follow the same procedure outlined earlier, except that you'll record all of your code directly onto the ribbon menu bar rather than in a dedicated macro tab. After recording your code, go back to the main interface and highlight Ribbon " Modules " Utilities. Scroll down to the list labeled Quick Access Toolbar Items and drag the Mail button over to it.

Once you've completed this action, you'll notice that the icon depicting a person holding envelopes has appeared in the upper righthand corner of your status bar. If you hover your mouse pointer over it, you'll notice that the dropdown arrow shows a checkmark next to it indicating that the item was successfully added to the toolbar. But if you scroll further down, you'll discover that the icon isn't actually part of the Quick Access Menu anymore. Instead, it's located on the far more robust Customize Ribbon area.

Here you can edit every single aspect of the ribbon menus' appearance -- including placing icons wherever you wish along the length of the tabs. Just keep in mind that whatever items you place on the Quick Access Menu must remain visible while navigating around your sheets. Otherwise they could disappear unexpectedly, leaving you unable to access their functions.

After dragging the Mail icon onto the customribbon area, the final stage of configuration takes place. First, expand the pane on the right side called Application Tab Options. Choose Manage Rules from the Commands group on the top row. Under Conditions, locate List Box Input, tick off Send Message, and fill in the subject field with your desired title. Leave the body blank. Hit the Apply button and enjoy the automatic emailing power of Excel.

For additional help, read our guide detailing how to write your own Excel IF function.



How do I send a dynamic email from Excel?

Let's say that you already created a report in Excel that produces several different types of output based on specific criteria. Rather than retype the entire thing every time someone wants to view the latest stats, why not combine the most recent data with customized notes for individuals who request it? By combining a static template with conditional formatting, you can produce a personalized newsletter that anyone else can easily reproduce. Here's how to do it.

1. Create a table listing all recipients whose responses you would like to track. Put headers for each column to identify their identities. Use headings like Subject Line, Recipient Number, Date Received, etc. Headers allow users to quickly scan rows for relevant information.

2. Select the cells containing the names/numbers of intended recipients, and then switch to Home tab " Font Group " Conditional Formatting. On the Styles panel, click New Rule... to create a rule condition for font color red. Set the format style to Fill Color, and leave Value empty. Enter #FF0000 into the Formula dropdown menu to assign the specified hexadecimal color to cells matching your chosen rules.

When finished, click OK to finish defining your rule. Repeat this process for each recipient cell.

3. Switch back to Normal mode and repeat the above steps for all columns displaying dates, times, and response rates. Remember that you shouldn't skip Step 3. No matter how many columns you define conditional formats for, always ensure that you complete the last step. Failure to do so could result in errors when trying to distribute copies of your newsletter.

4. Go ahead and adjust the colors of all cells corresponding to nonrespondents. Since the goal here is to track statistics, it doesn't matter much whether you mark them in green or yellow.

Lastly, remember to include your signature in the footer of your newsletter. Users will appreciate seeing your contact details alongside important news regarding your organization.

How do I create an email from Excel data?

While most people prefer writing letters, sometimes it makes sense to utilize Excel's built-in ability to automatically generate letters based on preselected data. To accomplish this, you'll need to create a series of templates first.

Create four columns for addresses, salutations, greetings, and signatures respectively. Each entry should consist of either the company name, department, extension, fax number, or phone number.


Author

Anyleads

San Francisco

We are the leading marketing automation platform serving more than 100,000 businesses daily. We operate in 3 countries, based in San Francisco, New York, Paris & London.

Join Anyleads to generate leads

Error! Impossible to register please verify the fields or the account already exists.. Error, domain not allowed. Error, use a business email. Welcome to the Anyleads experience!
More than +200 features to generate leads
Register to start generating leads

Create your account and start your 7 day free trial!

Error! Impossible to register please verify the fields or the account already exists.. Error, domain not allowed. Error, use a business email. Welcome to the Anyleads experience! By registering you agree to the Terms and conditions agreement.
More than +200 features to generate leads

We offer multiple products for your lead generation, discover them below!

>> Unlimited access to all products with one single licensecheck our pricing.