How to Send Email When Computer is Locked? - excel

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

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.

Task Scheduler Opens Excel file but keeps running and does not complete

I have the code below in a Module. I've tried using Workbook_Open in the 'ThisWorkbook' and I've tried using Auto_Open in the Sheet. Neither one would run the code upon opening the spreadsheet. This is why my code is in a Module. The program runs fine if I manually open it. However, when using the task scheduler it opens the excel file and keeps running. It doesn't execute the code. The code is just a simple email with an attachment.
As for Task Scheduler, In the General tab, I have Run only when the user is logged on, and Run with the highest privileges checked. I also have Wake the computer to run this task checked in conditions.
Sub Auto_Open()
Dim OutApp As Object
Dim OutMail As Object
Set OutApp = CreateObject("Outlook.Application")
Set OutMail = OutApp.CreateItem(0)
Application.DisplayAlerts = False
On Error Resume Next
With OutMail
.to = "bjenks#ormat.com"
.CC = ""
.BCC = ""
.Subject = "Test Workbook Open"
.Body = "Hi there"
.Attachments.Add ("C:\Users\bjenks\Desktop\Test.xlsx")
.Send 'or use .Display
End With
Set OutMail = Nothing
Set OutApp = Nothing
End Sub
I unchecked Run with the highest privileges and change to Public and it worked.

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.

Error While Sending Email through Outlook from Excel VBA

I have write a macro in outlook and excel vba, the description are:
1. Code in Outlook for Open Excel file if email subject line match :
Private Sub Items_ItemAdd(ByVal Item As Object)
If TypeOf Item Is Outlook.MailItem Then
'// Subject line here
If InStr(Item.Subject, "Run Dashboard") Then
Call openExcel
End If
End If
End Sub
Once Excel is open and dashboard has run then email has to be sent via excel.
vba and code:
Dim outapp As Object
Dim nmail As Object
Set outapp = CreateObject("Outlook.Application")
Set nmail = outapp.CreateItem(0)
With nmail
.To = "xxxxxx#xxxx.com"
.cc = ""
.bcc = ""
.Subject = flname
.htmlbody = RangetoHTML(Range("A1:" & Split(Cells(, lastcol1).Address, "$")(1) & lastrow1))
.attachments.Add ActiveWorkbook.FullName
.display
End With
On Error GoTo 0
Set nmail = Nothing
Set outapp = Nothing
Now I am facing the error on Set outapp = CreateObject("Outlook.Application")
This error is only showing if i open excel file through outlook email as mentioned in point 1, if i open file in normal way i.e. without outlook help, then code is running successfully.
Please help in the same.
Thanks in advance
Why do you need to automate Excel from Outlook and then Outlook from Excel?
Set outapp = CreateObject("Outlook.Application")
Instead you may get the running Outlook instance (if any) because only one instance of Outlook can be run simultaneously. See How to automate Outlook from another program and GetObject and CreateObject behavior of Office automation servers for more information.
Try to use the following line of code instead:
Set nmail = Application.CreateItem(olMailItem)
If you have multiple profiles in Outlook configured most probably you will need to use the Logon method of the Namespace class.

Calling a custom Ribbon button in another Application from VBA

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.

Resources