Excelmacros:如何在VBA脚本停止执行时获取通知

我在一台远程PC上运行一个macros,每5秒钟执行一次。

现在我想,如果出现错误,macros停止执行,我应该通过电子邮件通知或通知。

我怎样才能做到这一点?

error handling。

Sub MySub() On Error GoTo ErrorHandler ' Work done here... ' Screen for an expected error If somethingWentWrong = True Then Err.Raise Number:=myErrorNumber, Source:="MySub", _ Description:="This thing went wrong." ' Will now go to ErrorHandler End If ' More work done here... ExitProcedure: On Error Resume Next 'Cleanup code goes here... Exit Sub ErrorHandler: ' If an error occurs (anticipated or not), the following will be executed. Call SendEmailNotification( _ Recipient:="you@there.com", _ Subject:="Something went wrong.", _ Message:=Err.Number & vbCrLf & Err.Description & vbCrLf & Err.Source) ' Any other error handling goes here... Resume ExitProcedure End Sub 

要发送电子邮件,有各种各样的解决scheme。 searchCDO, MAPI , Sockmail 。 search这些将给你如何写你的SendEmailNotification子的例子。 单挑:没有一个是直截了当的。

您可以在error handling中添加邮件发送function。 如果macros正在执行的机器已正确设置Outlook,我相信你可以使用ActiveWorkbook.SendMail 。

如果这台电脑没有设置Outlook,则需要找出符合您的环境的邮件解决scheme。

它会看起来像:

 Sub MySub() On Error GoTo ProcError 'Your stuff ProcExit: Exit Sub ProcError: ActiveWorkbook.SendMail "your.mail@yourdomain.com", "Application failed!" Resume ProcExit End Sub