2013-12-16 72 views
0

我有一个MS Access 2010数据库,我想自动发送电子邮件。我已经设置了查询,但却陷入了CDO VBA的困境。他们查询被称为“qryEmails”,包含以下4个领域:CDO电子邮件自动化

ReturnCode, SalesOrderNumber, Name, EmailAddress 

我如何访问:

  1. 遍历每个记录并发送电子邮件给每个电子邮件地址上市
  2. 在每封电子邮件中,有一条消息将包含对前3个字段的引用,因此每条消息都会显示为个性化的
  3. 有动态主题,因此ReturnCode字段在每个主题中

我一直在尝试小步骤,到目前为止我收到了100个电子邮件到同一个地址。这里是我的代码(我已经使用XXX,我不想透露信息):

Dim rst As ADODB.Recordset 
Dim strSQL As String 
Dim strEmail As String 
Set rst = New ADODB.Recordset 
' 
strSQL = "[qryEmails]" 'source of recordset 
rst.Open strSQL, CurrentProject.Connection, adOpenKeyset, adLockOptimistic 
' 
Do While Not rst.EOF 
    strEmail = rst.Fields("EmailAddress") 

    Set objMessage = CreateObject("CDO.Message") 
    objMessage.Subject = "Your refund is:" ' 
    objMessage.FROM = """SENDER"" <[email protected]>" 
    objMessage.To = rst.Fields("EmailAddress") 
    objMessage.TextBody = objMessage.TextBody & rst(1) 


    '==Add fields to email body 
    'Do While strEmail = rst.Fields("EmailAddress") 

    'rst.MoveNext 
    'If rst.EOF Then Exit Do 
    'Loop 

' ========= SMTP server configuration 

     objMessage.Configuration.Fields.Item _ 
     ("http://schemas.microsoft.com/cdo/configuration/sendusing") = 2 

     'Name or IP of Remote SMTP Server 
     objMessage.Configuration.Fields.Item _ 
     ("http://schemas.microsoft.com/cdo/configuration/smtpserver") = "XXX" 

     'Server port (typically 25) 
     objMessage.Configuration.Fields.Item _ 
     ("http://schemas.microsoft.com/cdo/configuration/smtpserverport") = 25 

     objMessage.Configuration.Fields.Update 

     '==End remote SMTP server configuration section== 

     'Send email 
     objMessage.Send 
     'Clear variable for next loop 
     Set objMessage = Nothing 
    Loop 
rst.Close 
Set rst = Nothing 

任何想法,为什么这是发送100的电子邮件?目前为止,查询结果仅返回两个地址用于测试目的。

回答

1

在循环中,记录集保留在同一行上。并且由于记录集行不会改变,所以它永远不会到达rst.EOF

该代码包含禁用行MoveNext。取消注释该行。您可能想在Loop声明之前将其定位。

Do While Not rst.EOF 
    ' do everything you need for current record, 
    ' then move to the next record ... 
    rst.MoveNext 
Loop