使用VBA对电子邮件地址运行访问查询,以用作生成电子邮件的电子邮件收件人

时间:2019-04-12 19:59:07

标签: vba ms-access access-vba

我正在运行一个查询EmailList,该查询拉出访问表单上显示的人员的电子邮件地址。该查询本身运行正常,并在“电子邮件”字段中填充了预期的收件人。我想使用VBA将此查询中显示的电子邮件复制到新电子邮件,并将其列为收件人。我需要电子邮件为html,因为我在电子邮件正文中附加了超链接。

Set OutApp = CreateObject("outlook.application")
OutApp.Session.Logon
Set OutMail = OutApp.createitem(0)

Dim rs As DAO.Recordset
Dim qry As DAO.QueryDefs
Dim CurrentDb As DAO.Database
Dim OlApp As Object
Dim OlMail As Object
Dim ToRecipient As String

  Set OlApp = CreateObject("Outlook.Application")
  Set OlMail = OlApp.createitem(olmailitem)
  Set rs = CurrentDb.OpenRecordset("SELECT Email FROM [EmailList]")

  Do While rs.EOF = False
    ToRecipient = rs!Email
    OlMail.Recipients.Add ToRecipient
    rs.MoveNext
  Loop

With OutMail
    .Subject = "MOC"
    .HTMLbody = "<a href=""X:\MOC Training.accdb"">Click Here for Training</a><br>"
    .Display
End With
Set OutMail = Nothing
Set OutApp = Nothing

在玩这个游戏时,我的接收者只能是空白,或者在“设置rs”订单项中出现错误。我是VBA的新手,所以我不明白该错误。

请参见下面的SQL代码:

SELECT Employees.Email
FROM Employees LEFT JOIN Names2 ON Employees.Employee = Names2.[Names Trainee]
WHERE (((Names2.MOC)=[Forms]![Input MOC]![cboMOC#]));

2 个答案:

答案 0 :(得分:1)

相同类型的Outlook对象使用多个变量,然后不一致地使用变量。不要将CurrentDb用作声明的变量-它已经是一个固有常数。不需要ToRecipient变量。

此代码对我有用。

bible: 100 (colored as good)
math: 60 (colored as ok)
english: 40 (colored as bad)

答案 1 :(得分:0)

您的直接问题是OpenRecordset,与Outlook无关。因此,让我们暂时忽略Outlook位,着重解决OpenRecordset问题。

发生错误是因为OpenRecordset无法从组合框中检索值:

WHERE (((Names2.MOC)=[Forms]![Input MOC]![cboMOC#]))

相反,它将[Forms]![Input MOC]![cboMOC#]视为您尚未提供值的参数。因此,请在调用OpenRecordset之前提供该值。

将此代码粘贴到新过程中并运行它。您可以在立即窗口中查看Debug.Print的输出; Ctrl + g 将带您到达那里。

Dim db As DAO.Database
Dim rs As DAO.Recordset
Dim qdf As DAO.QueryDef
Dim strSelect As String
strSelect = "SELECT e.Email FROM Employees As e " & _
    "INNER JOIN Names2 As n ON e.Employee = n.[Names Trainee] " & _
    "WHERE n.MOC=[Forms]![Input MOC]![cboMOC#];"
Debug.Print "strSelect: " & strSelect
Debug.Print "combo box: " & [Forms]![Input MOC]![cboMOC#].Value

Set db = CurrentDb
Set qdf = db.CreateQueryDef(vbNullString, strSelect)
qdf.Parameters(0).Value = [Forms]![Input MOC]![cboMOC#].Value
Set rs = qdf.OpenRecordset
Do While Not rs.EOF
    Debug.Print rs!Email
    rs.MoveNext
Loop

如果记录集打开并在“立即”窗口中打印正确的数据,请修改原始代码以同样的方式处理记录集。如果此代码失败,请向我们显示 strSelect 的值和组合框,完整的错误消息以及该代码的哪一行触发该错误。