【发布时间】:2018-03-08 16:45:07
【问题描述】:
我正在使用 Excel VBA 宏在每天指定的时间发送自动电子邮件 (Outlook 2013),该电子邮件与 Windows 任务计划程序一起运行(我正在使用批处理文件来执行此操作)。当我在没有任务计划程序的情况下运行宏时,它会正常执行(发送电子邮件),但是当我使用任务计划程序时,我收到“运行时错误 429”,这仅在 VBA 宏尝试创建 Outlook 对象时发生:
Dim OutApp As Object
Dim OutMail As Object
Set OutApp = CreateObject("Outlook.Application") 'The error happens here
Set OutMail = OutApp.CreateItem(0)
On Error Resume Next
With OutMail
.to = "email@email.com"
.CC = ""
.BCC = ""
.Subject = "subj"
.Body = "body"
.Attachments.Add ActiveWorkbook.FullName
.Send
End With
On Error GoTo 0
Set OutMail = Nothing
Set OutApp = Nothing
只有在计算机上打开 Outlook 应用程序时才会发生上述错误。 现在我不明白的是:
为什么宏在没有任务计划程序的情况下可以正常工作(不管 Outlook 是否打开),为什么它不能在那里工作?
如何使用任务计划程序执行整个流程,而不依赖于打开或关闭 Outlook 应用程序? (即,无论打开/关闭哪些应用程序,我都希望宏运行)。
建议将不胜感激。
编辑:这是我用来执行宏的 VBScript 代码(以回应 LS_ᴅᴇᴠ 的问题):
Dim WshShell
Set WshShell = CreateObject("WScript.Shell")
' Create an Excel instance
Dim myExcelWorker
Set myExcelWorker = CreateObject("Excel.Application")
' Disable Excel UI elements
myExcelWorker.DisplayAlerts = False
myExcelWorker.AskToUpdateLinks = False
myExcelWorker.AlertBeforeOverwriting = False
myExcelWorker.FeatureInstall = msoFeatureInstallNone
' Tell Excel what the current working directory is
' (otherwise it can't find the files)
Dim strSaveDefaultPath
Dim strPath
strSaveDefaultPath = myExcelWorker.DefaultFilePath
strPath = WshShell.CurrentDirectory
myExcelWorker.DefaultFilePath = strPath
' Open the Workbook specified on the command-line
Dim oWorkBook
Dim strWorkerWB
strWorkerWB = strPath & "\____DailyReport.xlsm"
Set oWorkBook = myExcelWorker.Workbooks.Open(strWorkerWB)
' Build the macro name with the full path to the workbook
Dim strMacroName
strMacroName = "'" & strPath & "\____DailyReport.xlsm'" & "!Module1.____DailyRep"
on error resume next
' Run the calculation macro
myExcelWorker.Run strMacroName
if err.number <> 0 Then
' Error occurred - just close it down.
End If
err.clear
on error goto 0
'oWorkBook.Save
'oWorkBook.Close <<--- we don't need these two because we close the WB in the VBA macro
myExcelWorker.DefaultFilePath = strSaveDefaultPath
' Clean up and shut down
Set oWorkBook = Nothing
' Don’t Quit() Excel if there are other Excel instances
' running, Quit() will
'shut those down also
if myExcelWorker.Workbooks.Count = 0 Then
myExcelWorker.Quit
End If
Set myExcelWorker = Nothing
Set WshShell = Nothing
【问题讨论】:
-
这是一个 Excel 宏,你在任务调度器中放了什么批次?
-
@LS_ᴅᴇᴠ 我使用的是此处描述的 VBScript:Excel: Running Excel on Windows Task Scheduler,我的批处理文件如下所示:
start "" "D:\Documents\Macros\___\Run__Rep.vbs" -
那么,另一个问题... VBS包含什么?
-
@LS_ᴅᴇᴠ 我已经编辑了帖子(添加了 VBS 代码)。