vba - VBA代码出错时自动发送邮件

标签 vba error-handling outlook

我正在编写一个 VBA 宏,供非 VBA 用户使用。因此,我想在代码中嵌入一个系统,当代码抛出错误时,自动从宏用户的 outlook 帐户向我发送一封电子邮件。这可以用 VBA 实现吗?此外,用户不会拥有对其帐户的管理员访问权限,这会产生问题吗?在此先感谢您的帮助!

编辑 - 我现在知道这是可能的,并且也有相同的 vba 代码(见下文)。但是,我们是否可以消除尝试自动发送电子邮件时弹出的“安全警告框”。另外,我想在电子邮件中附上错误文件。如果我能在这方面得到一些帮助,那就太好了,谢谢!

最佳答案

试试这个。 未经测试

Option Explicit

Sub Sample()
    On Error GoTo Whoa

    '
    '~~> Rest of the Code
    '

    Exit Sub
 Whoa:
    Set OutApp = CreateObject("Outlook.Application")
    Set OutMail = OutApp.CreateItem(0)

    With OutMail
        .To = "abc@abc.com"
        .Subject = "Error Occured - Error Number " & Err.Number
        .Body = Err.Description

        .Display '~~> Change this to .Send for sending the email
    End With

    Set OutApp = Nothing: Set OutMail = Nothing
End Sub

跟进

Is there a way I can also attach the excel file having the macro? I will edit main question as well to reflect this. – hardikudeshi 5 mins ago

试试这个。

Option Explicit

Private Declare Function GetTempPath _
Lib "kernel32" Alias "GetTempPathA" _
(ByVal nBufferLength As Long, _
ByVal lpBuffer As String) As Long

Private Const MAX_PATH As Long = 260

Sub Sample()
    Dim OutApp As Object, OutMail As Object
    Dim wb As Workbook

    On Error GoTo Whoa

    '
    '~~> Rest of the Code
    '

    Exit Sub
 Whoa:
    Set wb = ThisWorkbook

    Application.DisplayAlerts = False
    wb.SaveAs TempPath & "ErroringFile.xls", FileFormat:= _
    xlNormal
    Application.DisplayAlerts = True

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

    With OutMail
        .To = "abc@abc.com"
        .Subject = "Error Occured - Error Number " & Err.Number
        .Body = Err.Description
        .Attachments.Add TempPath & "ErroringFile.xls"

        .Display '~~> Chnage this to .Send for sending the email
    End With

    Set OutApp = Nothing: Set OutMail = Nothing
End Sub

Function TempPath() As String
    TempPath = String$(MAX_PATH, Chr$(0))
    GetTempPath MAX_PATH, TempPath
    TempPath = Replace(TempPath, Chr$(0), "")
End Function

关于vba - VBA代码出错时自动发送邮件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10622912/

相关文章:

vba - 无效的属性分配?

excel - 如何根据月份检查单元格的范围/列并复制它们

excel - 删除表中的空白行

返回 NullPointerException 的 Java 文件

vba - 在 Outlook 中使用 VBA 收集收到的电子邮件的统计信息

internet-explorer - 使用VBA操作网页上的单选按钮

java - Java越界错误

angular - 错误: Uncaught (in promise) - Angular error - NullInjectorError:

json - Odata查询Outlook Rest API

html - outlook 2007 不在电子邮件中显示图像按钮