1

我已经编写了一个代码来通过 excel 发送带有 Outlook 的电子邮件。但是我想在单击显示“电子邮件发送成功”的“发送”按钮时添加一个 MsgBox。但它不起作用。我可以帮忙吗

我尝试创建一个变量“Dim IsSent As Boolean”并在开始时将其设置为 False,然后在发送时将其设置为 True。但它不起作用。这是我的代码:

Sub subMail_Sheet_Outlook_Body()
    Dim rng As Range
    Dim OutApp As Object
    Dim OutMail As Object
    Dim IsSent As Boolean

    With Application
        .EnableEvents = False
        .ScreenUpdating = False
    End With

    Set IsSent = False
    Set rng = Nothing
    Set rng = ActiveSheet.UsedRange
    'You can also use a sheet name
    'Set rng = Sheets("YourSheet").UsedRange

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

    On Error Resume Next
    With OutMail
        .To = emailform.emailEnter.Value
        .CC = ""
        .BCC = ""
        .Subject = emailform.emailSubject.Value
        .HTMLBody = "Here" & RangetoHTML(rng)
        .Send  'or use .Display


    End With


    On Error GoTo 0

    With Application
        .EnableEvents = True
        .ScreenUpdating = True

        Set IsSent = True

        If IsSent = True Then
        MsgBox "Succes"
        Else
        MsgBox "Noooon"
        End If

    End With

    Set OutMail = Nothing
    Set OutApp = Nothing


End Sub

使用此代码,如果发送了邮件,我希望“成功”,如果不是,则希望“不成功”,但是我有一个错误消息:

编译错误:需要对象

4

3 回答 3

0

更改Set IsSent = FalseIsSent = FalsesinceISSent是一个布尔变量,而不是一个对象

于 2019-09-26T13:22:49.730 回答
0

Set 用于对象。布尔值是值。尝试在涉及 IsSent 变量的行上删除“Set”。

于 2019-09-26T13:22:53.673 回答
0

我认为您可以使用简单的On error GoTo并避免这种随机布尔条件

Sub subMail_Sheet_Outlook_Body()

On Error GoTo IFErrorMail

    Dim rng As Range
    Dim OutApp As Object
    Dim OutMail As Object

    With Application
        .EnableEvents = False
        .ScreenUpdating = False
    End With


    Set rng = Nothing
    Set rng = ActiveSheet.UsedRange
    'You can also use a sheet name
    'Set rng = Sheets("YourSheet").UsedRange

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


    With OutMail
        .To = emailform.emailEnter.Value
        .CC = ""
        .BCC = ""
        .Subject = emailform.emailSubject.Value
        .HTMLBody = "Here" & RangetoHTML(rng)
        .Send  'or use .Display


    End With


    With Application
        .EnableEvents = True
        .ScreenUpdating = True

    End With

MsgBox "Success"
If (Not (OutMail Is Nothing)) Then Set OutMail = Nothing
If (Not (OutApp Is Nothing)) Then Set OutApp = Nothing

Exit Sub

IFErrorMail:
If (Not (OutMail Is Nothing)) Then Set OutMail = Nothing
If (Not (OutApp Is Nothing)) Then Set OutApp = Nothing
MsgBox "Error Mail could not be sent"    
End Sub
于 2019-09-26T13:36:39.177 回答