在msgbox中显示单个db值

时间:2015-02-22 19:02:31

标签: vba ms-access access-vba ms-access-2007 ms-office

我在访问2007文件中有以下vba代码:

Private Sub Form_Load()

Dim a As String
Dim b As DAO.Recordset

a = " select col1 from table1 where id = 1 "
Set b = CurrentDb.OpenRecordset(a)

MsgBox (b)
b.Close

End Sub

但我在MsgBox (b)行上收到以下错误。知道为什么会这样吗?查询返回一个值,我想在消息框中显示该值。

2 个答案:

答案 0 :(得分:3)

如果您希望MsgBox显示记录集第一列中包含的值,您可以这样做......

MsgBox b(0)

但是,您实际上不需要打开记录集来检索该单个值。您可以使用DLookup表达式。

MsgBox DLookup("col1", "table1", "id = 1")

答案 1 :(得分:2)

Matteo提到你需要传递一个String或者可以转换为String的东西到MsgBox。在这种情况下,您可以在选择查询中指定字段。

Private Sub Form_Load()

    Dim a As String
    Dim b As DAO.Recordset

    a = " select col1 from table1 where id = 1 "
    Set b = CurrentDb.OpenRecordset(a)

    MsgBox b.Fields("col1")  ' Msgbox b("col1") should also work
    b.Close

End Sub
相关问题