VBA基于查询编写电子邮件正文,Loop?

时间:2012-12-21 17:26:45

标签: vba access-vba

我想通过VBA将查询中的所有记录写入电子邮件。

MyBodyText = MailList("AccountName") & "   -   " & MailList("ExpirationDate")

这就是我目前所拥有的,它显然可以直到某一点:它只在查询中写入第一条记录。我知道我需要某种循环来使它工作,但我不能为我的生活弄明白。

编辑:MailList定义如下

Set MailList = db.OpenRecordset("qryDateEmail")

edit2:按要求

Option Compare Database
Option Explicit

Public Function ExpirationDate()

Dim strSQL
Dim db As DAO.Database
Dim MailList As DAO.Recordset
Dim MyOutlook As Outlook.Application
Dim MyMail As Outlook.MailItem
Dim Subjectline As String
Dim BodyFile As String
Dim fso As FileSystemObject
Dim MyBody As TextStream
Dim MyBodyText As String
Dim MyDecision As String
Dim strReportName As String
Dim strEnroll As String
Dim strWho As String
Dim strEmail As String

Set fso = New FileSystemObject
Set MyOutlook = New Outlook.Application
Set db = CurrentDb()
Set MailList = db.OpenRecordset("qryDateEmail")

Subjectline$ = "Expiration Date" & " " & Date

Set MyMail = MyOutlook.CreateItem(olMailItem)

Do While Not MailList.EOF
MyBodyText = MailList("AccountName") & "   -   " & MailList("ExpirationDate")
MailList.MoveNext
Loop

MyMail.To = "" & ""
MyMail.CC = CurrentUser() & ""

MyMail.Subject = Subjectline$

MyMail.Body = MyBodyText
MyMail.Display

strEmail = Now()
strWho = CurrentUser()

Set MyMail = Nothing
Set MyOutlook = Nothing

End Function

我有一个我一直在搞乱的循环。

1 个答案:

答案 0 :(得分:1)

您可以遍历记录集,将每行中的值添加到正文中。

未经测试的航空代码:

With MailList
    Do While Not .EOF
        MyBodyText = MyBodyText & !AccountName & _
            "   -   " & !ExpirationDate & vbCrLf
        .MoveNext
    Loop
End With

现在我看到你在问题中添加了类似的代码。问题是代码每次都会覆盖MyBodyText的值。每次都附加到MyBodyText,而不是替换文字......

MyBodyText = MyBodyText & "new text"

而不是......

MyBodyText = "new text"