Calling a custom Ribbon button in another Application from VBA - excel

Normally my google skills aren't this bad. I am looking for a way to send an email with VBA and selecting a ribbon button. Basically I have a custom Ribbon button to encrypt emails, and I want it toggled on when the new email is created from VBA. I have been unable to find any samples. Any help would be appreciated
Sub SendMail()
Dim OutMail As Outlook.MailItem
Dim outapp As Outlook.Application
With Application
.EnableEvents = False
.ScreenUpdating = False
End With
Set outapp = CreateObject("Outlook.Application")
Set OutMail = outapp.CreateItem(0)
With OutMail
.To = "Email#place.thing"
.CC = ""
.BCC = ""
.Subject = "BACON"
.HTMLBody = "TESTING"
' .Send
.Display
End With
With Application
.EnableEvents = True
.ScreenUpdating = True
End With
Set OutMail = Nothing
Set outapp = Nothing
End Sub
So when a new email is created I want the "Encrypt" button pressed (see picture below) . It is a toggle button.
http://i.stack.imgur.com/JWwgO.png

Something like this should do the trick. I am able to successfully invoke a ribbon button's procedure in an external application (tested in PPT because I don't have a readily available Outlook Add-in with customUI, but same approach should work for Outlook, Word, etc.)
Option Explicit
Sub CallExternalRibbon(app As Object, _
AddInName as String, _
ModuleName As String, _
ProcedureName As String)
'###
' runs a specific procedure from another application/Add-in
' AddInName is the name of the Add-in's VBAProject
' ModuleName should NOT use Option Private Module
' ProcedureName should be declared Public
'
' May also require change to application's Trust Center settings
' (specifically: allow access to VBAProject Object Model)
'###
Dim externalProcedure As String
'## concatenate the procedure string
externalProcedure = AddInName & "!" & ModuleName & "." & ProcedureName
'## run the external procedure from that application
app.Run externalProcedure
End Sub
Call this like so, before the .Send. Modify the string arguments to your specific needs:
Call CallExternalRibbon(outApp, _
"AddIn_VBAProject_Name", _
"Module_Name", _
"Callback_Procedure_Name")
NOTES:
Not thoroughly tested, but works in simple cases. You may run in to some issues by starting a process thread in another application.
This will work for an Add-in that is created with CustomUI and XML/VBA callbacks. It may not work and has not been tested on any proprietary Add-in or other COM Add-in that you might have installed from a third party.

Related

Convert from sending email immediately from Excel to displaying in Outlook

In this code an Excel file table from active sheet is sent directly via email.
I need to change it to same result only difference is I need it open in Outlook as draft and not send it (there will be added more of text etc.).
I tried .Display but it won't open Outlook new email, it is displayed in Excel.
Sub Send()
Dim AWorksheet As Worksheet
Dim Sendrng As Range
Dim rng As Range
On Error GoTo StopMacro
With Application
.ScreenUpdating = False
.EnableEvents = False
End With
'Fill in the Worksheet/range you want to mail
'Note: if you use one cell it will send the whole worksheet
Set Sendrng = Range("B1:M44")
'Remember the activesheet
Set AWorksheet = ActiveSheet
With Sendrng
' Select the worksheet with the range you want to send
.Parent.Select
'Remember the ActiveCell on that worksheet
Set rng = ActiveCell
'Select the range you want to mail
.Select
' Create the mail and send it
ActiveWorkbook.EnvelopeVisible = True
With .Parent.MailEnvelope
' Set the optional introduction field thats adds
' some header text to the email body.
.Introduction = "Dear All," & vbNewLine & vbNewLine & "Please find XXX."
With .Item
.To = "XXXX"
.Subject = "XXX"
.Send
End With
End With
'select the original ActiveCell
rng.Select
End With
'Activate the sheet that was active before you run the macro
AWorksheet.Select
StopMacro:
With Application
Replace .Send with .Display. If you want to wait for the user to either click on the Send button or dismiss the message, use .Display(true) to show it modally.
You can automate Outlook directly from an Excel macro where you could display a new mail item to a user. For example, the following code creates a new mail items, set up properties on the item and then display it for a user:
variables declared as a specific object type ie. specific to the application which is being automated:
Dim applOL As Outlook.Application
Dim miOL As Outlook.MailItem
'Create a new instance of the Outlook application. Set the Application object as follows:
Set applOL = New Outlook.Application
'create mail item:
Set miOL = applOL.CreateItem(olMailItem)
With miOL
.To = "info#test.com"
.CC = ""
.Importance = olImportanceLow
.Subject = "Mail Automation"
.Body = "Sending the Active Excel Workbook as attachment!"
'add host workbook as an attachment to the mail:
.Attachments.Add ActiveWorkbook.FullName
.ReadReceiptRequested = True
.Display
End With
'clear the object variables:
Set applOL = Nothing
Set miOL = Nothing
Don't forget to add an Outlook COM reference to your VBA project in Excel. See Automating Outlook from a Visual Basic Application for more information.

MailItem.GetInspector.WordEditor in Office 2016 generates Application-defined or object defined error

I wrote an Excel macro to send email from a spreadsheet. It works on Office 2013, but not Office 2016.
I looked at the VBA differences between Office 2013 and 2016, but couldn't see anything about changes to the inspector or word editor for message objects.
Once it gets to .GetInspector.WordEditor it throws:
Run-time error '287':
Application-defined or object defined error
Here is the relevant part of the macro:
Sub SendEmail()
Dim actSheet As Worksheet
Set actSheet = ActiveSheet
'directories of attachment and email template
Dim dirEmail as String, dirAttach As String
' Directory of email template as word document
dirEmail = _
"Path_To_Word_Doc_Email_Body"
' Directories of attachments
dirAttach = _
"Path_To_Attachment"
' Email Subject line
Dim subjEmail As String
subjEmail = "Email Subject"
Dim wordApp As Word.Application
Dim docEmail As Word.Document
' Opens email template and copies it
Set wordApp = New Word.Application
Set docEmail = wordApp.Documents.Open(dirEmail, ReadOnly:=True)
docEmail.Content.Copy
Dim OutApp As Outlook.Application
Set OutApp = New Outlook.Application
Dim OutMail As MailItem
Dim outEdit As Word.Document
' The names/emails to send to
Dim docName As String, sendEmail As String, ccEmail As String, siteName As String
Dim corName As String
Dim row As Integer
For row = 2 To 20
sendName = actSheet.Cells(row, 1)
sendEmail = actSheet.Cells(row, 2)
ccEmail = actSheet.Cells(row, 3)
siteName = actSheet.Cells(row, 4)
Set OutMail = OutApp.CreateItem(olMailItem)
With OutMail
.SendUsingAccount = OutApp.Session.Accounts.Item(1)
.To = sendEmail
.CC = ccEmail
.Subject = subjEmail & " (Site: " & siteName & ")"
Set outEdit = .GetInspector.WordEditor
outEdit.Content.Paste
outEdit.Range(0).InsertBefore ("Dear " & sendName & "," & vbNewLine)
.Attachments.Add dirAttach
.Display
'.Send
End With
Debug.Print row
Set OutMail = Nothing
Set outEdit = Nothing
Next row
docEmail.Close False
wordApp.Quit
End Sub
Things I've tried based on suggestions:
Checked Outlook settings - default is HTML text
Moved .display over .GetInspector.WordEditor
Ensure Word is the default email editor. From the Inspector.WordEditor dox:
The WordEditor property is only valid if the IsWordMail method returns True and the EditorType property is olEditorWord . The returned WordDocument object provides access to most of the Word object model...
Further, ensure that Outlook is configured to send Rich Text or HTML emails, not plain text.
I am not entirely sure if I had the same issue as you, but the call to GetInspector started failing for me after upgrading Office 2016. So to be clear it worked with Office 2016 and then stopped working after the latest update.
The following workaround worked for me
dim item : set item = Addin.Outlook.CreateItemFromTemplate(Filename)
Outlook.Inspectors.Add(item) ' Outlook is the application object
it only appears to work if I add the item straight after creating it, setting properties on it and then adding it did not work.
Note: I have not tested with CreateItem instead of CreateItemFromTemplate. The second line was added and unnecessary prior to the Office update.
Problem:
For security purposes, the HTMLBody, HTMLEditor, Body and WordEditor properties all are subject to address-information security prompts because the body of a message often contains the sender's or other people's e-mail addresses. And, if Group Policy does not permit then these prompts do not come on-screen. In simple words, as a developer, you are bound to change your code, because neither registry changes can be made nor group policy can be modified.
Hence, if your code suddenly stopped working after migrating to Office 365 or for any other reasons, please refer to the solutions below. Comments have been added for easy understanding and implementation.
Solution 1:
If you have administrative rights then try the registry changes given at below link:
https://support.microsoft.com/en-au/help/926512/information-for-administrators-about-e-mail-security-settings-in-outlo
However, as developer, I recommend a code that's rather compatible with all versions of Excel instead of making system changes because system changes will be required on each end user's machine as well.
Solution 2: VBA Code
Code Compatible: Excel 2003, Excel 2007, Excel 2010, Excel 2013, Excel 2016, Office 365
Option Explicit
Sub Create_Email(ByVal strTo As String, ByVal strSubject As String)
Dim rngToPicture As Range
Dim outlookApp As Object
Dim Outmail As Object
Dim strTempFilePath As String
Dim strTempFileName As String
'Name it anything, doesn't matter
strTempFileName = "RangeAsPNG"
'rngToPicture is defined as NAMED RANGE in the workbook, do modify this name before use
Set rngToPicture = Range("rngToPicture")
Set outlookApp = CreateObject("Outlook.Application")
Set Outmail = outlookApp.CreateItem(olMailItem)
'Create an email
With Outmail
.To = strTo
.Subject = strSubject
'Create the range as a PNG file and store it in temp folder
Call createPNG(rngToPicture, strTempFileName)
'Embed the image in Outlook
strTempFilePath = Environ$("temp") & "\" & strTempFileName & ".png"
.Attachments.Add strTempFilePath, olByValue, 0
'Change the HTML below to add Header (Dear John) or signature (Kind Regards) using newline tag (<br />)
.HTMLBody = "<img src='cid:DashboardFile.png' style='border:0'>"
.Display
End With
Set Outmail = Nothing
Set outlookApp = Nothing
Set rngToPicture = Nothing
End Sub
Sub createPNG(ByRef rngToPicture As Range, nameFile As String)
Dim wksName As String
wksName = rngToPicture.Parent.Name
'Delete the existing PNG file of same name, if exists
On Error Resume Next
Kill Environ$("temp") & "\" & nameFile & ".png"
On Error GoTo 0
'Copy the range as picture
rngToPicture.CopyPicture
'Paste the picture in Chart area of same dimensions
With ThisWorkbook.Worksheets(wksName).ChartObjects.Add(rngToPicture.Left, rngToPicture.Top, rngToPicture.Width, rngToPicture.Height)
.Activate
.Chart.Paste
'Export the chart as PNG File to Temp folder
.Chart.Export Environ$("temp") & "\" & nameFile & ".png", "PNG"
End With
Worksheets(wksName).ChartObjects(Worksheets(wksName).ChartObjects.Count).Delete
End Sub
Try moving the editor to the first action...
...
With OutMail
Set outEdit = .GetInspector.WordEditor
outEdit.Content.Paste
.SendUsingAccount = OutApp.Session.Accounts.Item(1)
.To = sendEmail
.CC = ccEmail
.Subject = subjEmail & " (Site: " & siteName & ")"
...

Email sent with VBA using Task Scheduler gets stuck in Outbox

I have some macros and Task Scheduler to launch Excel at a specified time, update some tables, create PDF documents from those tables and then email those PDF documents to select individuals.
Sometimes the email gets stuck in the Outbox and does not send until I open up Outlook.
Here is the code for sending the email:
Option Explicit
Public strFileName As String
Sub EmailPDFAsAttachment()
'This macro grabs the file path and stores as a concatenation/variable. Then it emails the file to whomever you specify.
' Works in Excel 2000, Excel 2002, Excel 2003, Excel 2007, Excel 2010, Outlook 2000, Outlook 2002, Outlook 2003, Outlook 2007, Outlook 2010.
' This example sends the last saved version of the Activeworkbook object .
Dim OutApp As Object
Dim OutMail As Object
Dim FilePath As String
'This part is setting the strings and objects to be files to grab with their associated filepath. (e.g. FilePath is setting itself equal to the text where we plan to set up each report)
FilePath = "\\"ServerNameHere"\UserFolders\_AutoRep\DA\PDFs\SealantsVS1SurfaceRestore\" _
& strFileName & ".pdf"
With Application
.EnableEvents = True
.ScreenUpdating = True
' End With
'Below is where it creats the actual email and opens up outlook.
Set OutApp = CreateObject("Outlook.Application")
Set OutMail = OutApp.CreateItem(0)
On Error Resume Next
' ******Make sure to set the .To to only recipients that are required to view it. Separate email addresses with a semicolon (;).
' Current distribution list:
'
With OutMail
.To = "example#Example.com"
.CC = ""
.BCC = ""
.Subject = strFileName
.HTMLBody = "Hello all!" & "<br>" & _
"Here is this month's report for the Sealants vs Surface Restore. It goes as granular as to by show results by provider." & "<br>" & _
"Let me know what you think or any comments or questions you have!" & "<br>" & _
vbNewLine & .HTMLBody
'Here it attached the file, saves the email as a draft, and then sends the file if everything checks out.
.Attachments.Add FilePath
.Send
End With
On Error GoTo 0
' With Application
' .EnableEvents = True
' .ScreenUpdating = True
End With
'This closes out the Outlook application.
Set OutMail = Nothing
Set OutApp = Nothing
End Sub
After this completes, the Private sub jumps back to the macros in this workbook and quits MS Excel with the CloseWorkbook Application.
My tools reference library in Outlook's VBA settings:
My Trust Settings:
Macro Settings:
"Enable all macros" selected
"Apply macro security settings to installed add-ins" selected
The idea is to have this program run in the early morning and have these emails in the inbox of select individuals by the time they come in to work.
If anyone is still looking for an answer; this allows to actually send an email without opening outlook app.
Dim mySyncObjects As Outlook.SyncObjects
Dim syc As Outlook.SyncObject
Set mySyncObjects = Outlook.Application.GetNamespace("MAPI").SyncObjects
Set syc = mySyncObjects(1)
syc.start
Outlook, just like any other Office app, cannot run in a service(such as the Scheduler).
That being said, you need to force Outlook to perform SendReceive and wait for it to complete. Call Namespace.SendAndReceive or retrieve the first SyncObject object from the Namespace.SyncObjects collection, call SyncObject.Start and wait fro the SyncObject.SyncEnd event to fire.

Detecting User Choice with VBA Outmail application in Excel

I'm trying to figure out a way to detect whether or not the user clicks "Send" in the Outlook application that is displayed. I've tried reading the value of .Display similarly to how one would detect user input when using the FileDialog application (someInt = .Show), to no avail. I can't find any documentation on the Outmail Application, so any help would be greatly appreciated.
Set olApp = CreateObject("Outlook.Application")
Set Outmail = olApp.CreateItem(olMailItem)
With Outmail
.To = clientEmail
.CC = projectManagerEmail
.BCC = ""
.Subject = projectName & " (PO # " & poNumber & ", Job #" & projectNumber & ") - " & fileType & " (" & fileName & ")"
.Attachments.Add ActiveWorkbook.Path & "\" & fileType & "\" & folderName & "\" & fileName & ".pdf"
.Display
.Save
End With
I believe you need to intercept the Send operation in Outlook.
In Outlook, go to VBA Editor (Alt-F11), then paste below into the ThisOutlookSession under Microsoft Outlook Objects.
Make sure your operations works in Outlook, then close Outlook. You may have to Sign the code, change Macro Security Settings depending on your environment. Value of Cancel is what determines if the user has clicked Send (e.g. clicked -> Cancel=False).
Since there is no direct way to get the value of Cancel, may be you have to create a unique text file in local temp folder and pick it up in Excel to indicate it is Sent.
Private Sub Application_ItemSend(ByVal oItem As Object, Cancel As Boolean)
' Add Operations or Sub calls here
MyCheck01 oItem, bCancel
End Sub
Private Sub MyCheck01(ByVal oItem As Object, Cancel As Boolean)
' Do operations here. If Send is to be aborted, set Cancel to True.
End Sub
You will also need to define this olMailItem in Excel (Const olMailItem = 0).

How to Send Email When Computer is Locked?

I want to send Outlook emails using Excel VBA.
The code Sendupdate works when run manually.
My second macro StartTimer is intended to execute the above at a set time when I am not at my desk.
When the computer is locked the email does not send. When I come back to my desk the email is hanging there as a draft, and I need to click the send button.
Sub SendUpdate()
Recipient = "x#y.com"
Subj = "update"
Dim msg As String
msg = "hello”
HLink = "mailto:" & Recipient & "?"
HLink = HLink & "subject=" & Subj & "&"
HLink = HLink & "body=" & msg
ActiveWorkbook.FollowHyperlink (HLink)
Application.Wait (Now + TimeValue("0:00:01"))
Application.SendKeys "%s"
End Sub
Sub StartTimer()
Application.OnTime TimeValue("18:00:00"), "SendUpdate"
End Sub
Is there a way to make sure the email gets pushed?
I will break this "Tutorial" in 3 steps
1) Writing your Excel Macro
2) Preparing your vbscript file
3) Setting the task in Windows Task Scheduler
WRITING THE EXCEL MACRO
Open a new File in Excel and in the module, paste this code
Option Explicit
Const strTo As String = "abc#abc.com"
Const strCC As String = "def#abc.com" '<~~ change "def#abc.com" to "" if you do not want to CC
Const strBCC As String = "ghi#abc.com" '<~~ change "ghi#abc.com" to "" if you do not want to BCC
Sub Sample()
Dim OutApp As Object, OutMail As Object
Dim strbody As String, strSubject As String
strSubject = "Hello World"
strbody = "This is the message for the body"
Set OutApp = CreateObject("Outlook.Application")
Set OutMail = OutApp.CreateItem(0)
On Error Resume Next
With OutMail
.To = strTo
.CC = strCC
.BCC = strBCC
.Subject = "This is the Subject line"
.Body = strbody
.Send
End With
On Error GoTo 0
Set OutMail = Nothing
Set OutApp = Nothing
End Sub
Save the Excel File as C:\Tester.Xlsm if you are using Excel 2007 onwards or C:\Tester.Xls if you are using Excel 2003 and exit
PREPARING THE VBSCRIPT FILE
Open Notepad and then paste this code. Change the extension ".xls" as applicable.
Dim xlApp
Dim xlBook
Set xlApp = CreateObject("Excel.Application")
Set xlBook = xlApp.Workbooks.Open("C:\Tester.xls", 0, True)
xlApp.Run "Sample"
xlBook.Close
xlApp.Quit
Set xlBook = Nothing
Set xlApp = Nothing
Save the File as Tester.vbs and close it
SETTING UP THE TASK IN WINDOWS TASK SCHEDULER
Could you confirm your windows operating system? – Siddharth Rout 36 mins ago
Windows XP. Its my work computer (so has the usual logins etc). – keynesiancross 18 mins ago
Click on the Start Button | All Programs | Accessories | System Tools | Schedule Tasks to get this window
Double click on "Add Scheduled Task" to get this window
Click Next
Click on "Browse" and select the vbs file that we created earlier and click on "open"
The next window that you get is crucial as it is here we need to mention when script needs to run
After you have done the needful, click on next.
In this window, enter your login details so that the script can run even when your screen is locked.
Click "Next" when done and then click "Finish" in the next window. Your task scheduler now looks like this
And you are done
Lock your pc and go take a coffee break ;) When you come back (depending on what time you set in the task scheduler and how much time is your break), the email would have been sent.
HTH
I used HTML and JavaScript setInterval to run vba code to overcome such problem.
Code:
<html>
<script>
var flag = false;
var xlApp;
var xlBook;
var i = 0;
function processExcel()
{
//Open the excel containing macro for the first time
if(flag==false)
{
xlApp = new ActiveXObject ( "Excel.Application" );
//Your Excel containing VBA code
xlBook=xlApp.Workbooks.Open("Count1.2.xlsm")
}
// "a" is the VBA macro
xlApp.Run("a");
flag=true;
i++;
window.status="Last Updated " + new Date();
}
var w
function run()
{
processExcel();
w= setInterval("processExcel()",120000);
}
function stop()
{
clearInterval(w);
}
</script>
<body >
<input type="button" value="Start" onclick="run()" />
<input type="button" value="Stop" onclick="stop()"/>
</body>
</html>
SendKeys is likely the culprit. I still use CDO to send emails via Excel VBA. This should get you started: http://www.rondebruin.nl/cdo.htm

Resources