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.
Related
Question: Is it possible to create a macro that opens outlook in a web browser and populates the fields of a new message as well as attach a file? The outlook portion of the current macro only opens outlook in a browser.
ActiveWorkbook.FollowHyperlink Address:="https://outlook.office365.com/mail/**shared mailbox address**"
Background: I am trying to update an excel macro that currently saves a pdf of the sheet, opens the outlook application, fills out the necessary fields and attaches the saved pdf to the email. This macro has worked fine, but we have recently moved to using a shared mailbox to send the message. Now the users have encountered problems sending from the shared mailbox using the outlook application. The solution is to use outlook in the browser (edge), but the macro I currently have can only open outlook in the browser and requires the user to fill out all the fields and find and attach the saved pdf. There have been problems with this and I was hoping there was a way to automate the process like our old macro would.
Old macro:
Set OlApp = CreateObject("Outlook.Application")
Set NewMail = OlApp.CreateItem(0)
On Error Resume Next
With NewMail
.To = ReportName
.CC = ""
.Subject = TempFileName
.Body = ""
.Attachments.Add FileFullPath '--- full path of the pdf where it is saved
.Display '.Send or use .Display to show you the email before sending it.
End With
On Error GoTo 0
Well, Yes and No.
Yes, you can get VBA to do this... but No, it won't be remotely as easy as running it through the desktop application.
A workaround that still uses desktop application, is to
Give all users that need to send the email access to this inbox from their own desktop apps.
Use the ".SendUsingAccount" property
Sub ExampleSub()
Dim OLApp As Object
Dim NewMail As Object
Set OLApp = CreateObject("Outlook.Application")
Set NewMail = OLApp.CreateItem(0)
On Error Resume Next
With NewMail
.SentOnBehalfOfName = "MySecondaryAddress#Domain.com"
.To = "someaddress#gmail.com"
.CC = ""
.Subject = "Example Subject"
.Body = "Good Morning..."
'.Attachments.Add FileFullPath '--- full path of the pdf where it is saved
.Display '.Send or use .Display to show you the email before sending it.
End With
On Error GoTo 0
End Sub
I send an email with VBA. A classification is popped up for each email and it needs to be set by hand. I am trying to work around this in the code.
I found a code to send emails: Mail a message with outlook via VBA.
After fixing few things, the following code is working.
Sub sendEmail()
'For Tips see: http://www.rondebruin.nl/win/winmail/Outlook/tips.htm
'Working in Office 2000-2016
Dim OutApp As Object
Dim OutMail As Object
Dim cell As Range
Application.ScreenUpdating = False
Application.EnableEvents = False
Set OutApp = CreateObject("Outlook.Application")
On Error GoTo cleanup
For Each cell In Columns("B").Cells.SpecialCells(xlCellTypeConstants)
Set OutMail = OutApp.CreateItem(0)
On Error Resume Next
With OutMail
.To = cell.Value
.Subject = "Reminder"
.Body = "Dear " & Cells(cell.Row, "A").Value _
& vbNewLine & vbNewLine & _
"Please Finish your course " & Cells(cell.Row, "C") & _
" before expiry date."
.Send 'Or use Display
End With
On Error GoTo 0
Set OutMail = Nothing
Next cell
cleanup:
Set OutApp = Nothing
Application.ScreenUpdating = True
End Sub
The problem is that after sending emails from the list to for example 10 persons, I need to click on classification pop up 10 times.
I found this: How to save workbook and handle TITUS (or any other document classification add-in) popup?
I tried .EnableEvents = False before .Send. I am not sure if this does serve me.
How to use this in my case? Is it doable to disable it, work around it, or even set a classification within the code?
There is a workaround, but you have to do it in Outlook Developer itself. You can set up an event handler in Outlook which triggers a macro. So, in this case, Outlook could watch for a message to be created with a specific subject line (as an example), and THAT would trigger the script below, which bypasses TITUS.
'Sets Titus Mail settings and sends mail
With AOMailMsg
objMsg.ItemProperties.Add("ABCDE.Registered To", olText) = "My Companies"
objMsg.ItemProperties.Add("ABCDE.Classification", olText) = "Internal"
objMsg.UserProperties.Add("ABCDE.Registered To", olText) = "My Companies"
objMsg.UserProperties.Add("ABCDE.Classification", olText) = "Internal"
objMsg.UserProperties.Add("TITUSAutomatedClassification", olText) = _
"TLPropertyRoot=ABCDE;.Registered To=My Companies;.Classification=Internal;"
objMsg.Send
End With
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.
I am trying to open an Outlook 2010 email template with Excel. I get the following error:
"Run-time error '-2147287038 (80030002)':
Cannot open file:
C:\My\Path\MyTemplate.oft. The file may not exist, you may not have permission to open it, or it may be open in another program. Right-click the folder that contains the file, and then click Properties to check your permissions for the folder."
The file exists (in the right place), I checked permissions (as far as I know how), and the file is not open.
Sub Mail_experiment()
Dim OutApp As Outlook.Application
Dim OutMail As Outlook.mailitem
Set OutApp = CreateObject("Outlook.Application")
Set OutMail = OutApp.CreateItemFromTemplate("C:\My\Path\MyTemplate.oft")
On Error Resume Next
With OutMail
.to = "myEmail#aol.com"
.CC = ""
.BCC = ""
.Subject = "This is my Subject line"
.Send
End With
On Error GoTo 0
Set OutMail = Nothing
Set OutApp = Nothing
End Sub
"I tried my code on a different computer and it worked. I went back and changed the file name of my template, as the previous name was in all capitals (shouldn't matter, right?). I got a message about needing to be an administrator to do this, which I thought was strange since this is my personal home computer. However, when I clicked "continue" it went ahead and changed the name. Now it works. – David Elphee Sep 14 '14 at 13:23"
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