简体   繁体   中英

Send email automatically using outlook from excel

I am trying to send an open workbook (Excel) every day at 5pm. Here is my code:

I put this one in a module

Sub SendEmail()

    Dim OutApp As Object
    Dim OutMail As Object
    Set OutApp = CreateObject("Outlook.Application")
    Set OutMail = OutApp.CreateItem(0)

    With OutMail
        .To = "yourmail"
        .CC = ""
        .BCC = ""
        .Subject = "Report"
        .Body = "Hello!"
        .Attachments.Add ActiveWorkbook.FullName

        .Send
    End With

    Set OutMail = Nothing
    Set OutApp = Nothing
    Application.OnTime TimeValue("17:00:00"), "SendEmail"

End Sub

and i put this one in ThisWorkbook

Sub Workbook_Open()

    Application.OnTime TimeValue("17:00:00"), "SendEmail"
End Sub

My workbook is open all the time. I can't get the email, except I hit the run button in Excel. I want it do automatically everyday.

What you should do is add a new sub that sets up the time schedule that is called from the open command and the email, which will cause it to reset daily.

Add this Sub:

Sub SetSchedule()

Application.OnTime TimeValue("17:00:00"), "SendEmail"

Application.OnTime TimeValue("23:59:00"), "SetSchedule"

End Sub

And call it from the open sub:

Sub Workbook_Open()

    Call SetSchedule

End Sub

You can then delete the Application.OnTime call from the email sub itself

Your best option will be a simple Recurring task Item set it by using a reminder to recur everyday at 17:00

Example: Create your custom Task Item to recur at 1700

Add the following code to ThisOutlookSession

Option Explicit
Private Sub Application_Reminder(ByVal item As Object)
'   Now call your VBA Code

End Sub

As soon as reminder fires, your email will be sent automatically.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM