VBA Access从db获取字符串

时间:2013-05-12 18:42:45

标签: vba ms-access access-vba

我有一个包含电子邮件地址列的表格。

我想获取这些电子邮件地址并向他们发送邮件。 我的问题是我不知道如何获取地址。 我想得到一个字符串

me@email.com;me2@email.com;me3@email.com...etc

如何获取此字符串以将其传递给配方?

1 个答案:

答案 0 :(得分:2)

从记忆中(未经测试):

Dim db As DAO.Database, rs As DAO.Recordset
Dim s As String

Set db = CurrentDb
Set rs = db.OpenRecordset("SELECT email FROM myTable WHERE ...")
Do While Not rs.EOF
    If s = "" Then
        s = rs!email
    Else
        s = s & ";" & rs!email
    End If
    rs.MoveNext
Loop
rs.Close: Set rs = Nothing
db.Close: Set db = Nothing

由于从查询中连接字符串是一项常见任务,我建议创建一个可重用的函数:

Public Function ConcatenateFromSql(ByVal sql As  String, _
                                   Optional ByVal delimiter As String = ";") As String
    Dim db As DAO.Database, rs As DAO.Recordset
    Dim s As String

    Set db = CurrentDb
    Set rs = db.OpenRecordset(sql)
    Do While Not rs.EOF
        If s = "" Then
            s = rs(0)
        Else
            s = s & delimiter & rs(0)
        End If
        rs.MoveNext
    Loop
    rs.Close: Set rs = Nothing
    db.Close: Set db = Nothing

    ConcatenateFromSql = s
End Function