来自 MS Access 表单的电子邮件

问题描述

我有一个带有事件过程的按钮,用于更新表单上的多个字段,在我尝试添加代码以发送电子邮件之前,它可以正常工作。

在这里找到了代码修改了我的字段名称。我没有收到任何错误,它只是不发送电子邮件。我使用的是 Office 365 和 Windows 10。

我也希望能够在电子邮件发送之前查看它,但还没有找到任何关于如何执行此操作的信息。任何帮助将不胜感激! :)

Dim oApp As New outlook.application
Dim oEmail As Outlook.MailItem

Set oEmail = oApp.CreateItem(olMailItem)

oEmail.To = Me.EmailRule
oEmail.Subject = Me.Subject.Value
oEmail.Body = Me.txtBody.Value
If Len(Me.Attachment) > 0 Then
    oEmail.Attachments.Add Me.Attachment.Value
End If
With oEmail
    If Not IsNull(.To) And Not IsNull(.Subject) And Not IsNull(.Body) Then
        MsgBox "Email Sent!"
    Else
        MsgBox "please fill out the required fields."
    End If
End With

解决方法

如果您想查看,则需要 oEmail.SendoEmail.Display

为 Null 测试 oEmail.To/.Body/.Subject 将失败。这些永远不会为空 - 在提供其他数据之前,它们保持空字符串。可以在填充前使用 Debug.Print IsNull(oEmail.To) 进行验证。尝试使用 Null 填充将出现“无效使用 Null”错误。使用 Nz 处理可能的 Null:oEmail.To = Nz(Me.EmailRule,"")。然后在 oEmail 元素中测试空字符串:
If .To = "" Or .Subject = "" Or .Body = "" Then

或者在表单上测试控件:IsNull(Me.EmailRule) 并在尝试填充电子邮件元素之前执行此操作。考虑:

Dim oApp As Outlook.Application
Dim oEmail As Outlook.MailItem
If IsNull(Me.EmailRule) Or IsNull(Me.Subject) Or IsNull(Me.txtBody) Then
    MsgBox "please fill out the required fields."
Else
    Set oEmail = oApp.CreateItem(olMailItem)
    With oEmail
        .To = Me.EmailRule
        .Subject = Me.Subject
        .Body = Me.txtBody
        If Len(Me.Attachment) > 0 Then
            .Attachments.Add Me.Attachment
        End If
        .Display
    End With
End If

不相关但可能感兴趣:不需要键入 .Value,因为这是数据控件的默认属性。