从访问表vba创建一个数组

时间:2016-05-09 14:09:34

标签: arrays vba excel-vba loops excel

我正在尝试从访问中的表中提取名称和电子邮件地址列表,并使用该信息发送个性化电子邮件。所以我试图从访问中调用2列到一个数组,然后使用循环遍历每一行。我认为这将是最好的方式,但我对其他想法持开放态度。我已经能够生成一个代码,生成一个包含第一条记录的电子邮件,但我不知道如何获取剩余的记录:

Private Sub SMT()
Application.Run "VariablesForRanges"
strDB1 = ThisWorkbook.Path & "\database.accdb"
strqry1 = "SELECT table1.name, table2.Email"
strqry1 = strqry1 & " FROM table2 inner join table1 on table1.FULL_NAME=table2.Name"
strqry1 = strqry1 & " group by table1.name, table2.Email;"

Set cn1 = New ADODB.Connection
cn1.Open "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" & strDB1 & ";"
Set rs1 = New ADODB.Recordset

With rs1
    Set .ActiveConnection = cn1   
    .Open strqry1
End With

If rs1.BOF = True Then
    MsgBox "There Are No Records To Import", vbInformation
         Else
    Set OutApp = CreateObject("Outlook.Application")
    Set OutMail = OutApp.CreateItem(0)

strbody = "Hi " & rs1("name") & "," & vbNewLine & vbNewLine & _
"test" & vbNewLine & vbNewLine & _
"Best regards," & vbNewLine & _

On Error Resume Next
    With OutMail
    .To = rs1("Email")    
End With

On Error GoTo 0
    Set OutMail = Nothing
    Set OutApp = Nothing
End If
End Sub

任何有关创建数组和循环的帮助都将受到赞赏。谢谢。

1 个答案:

答案 0 :(得分:2)

为什么不直接遍历记录集?

Do While Not rs1.EOF
' create emails
    rs1.MoveNext
Loop