(VBA) For 循环和 DLookup (MS ACCESS)

(VBA) For loop and DLookup (MS ACCESS)

我有一个名为 TimeQuery 的查询。我希望 MsgBox 将显示所有 [start_hour] 值,其中 [id]=1 然后 2 等等...... 我有个问题。我什么时候使用:

a = DLookup("Hour([start_hour])", "TimeQuery", "[id]=1")

效果很好,但是使用[id]=counter时不显示。我在那个 For 循环之后也有一个 MsgBox,当 [id]=counter 它也没有显示 MsgBox。怎么了?

For counter = 1 To 3
Dim a As Variant
a = DLookup("Hour([start_hour])", "TimeQuery", "[id]=counter")
MsgBox (counter)
Next
Debug.Print ("")

如果你想使用它,你需要将你的变量连接成一个字符串,像这样:

For counter = 1 To 3
    Dim a As Variant

    a = DLookup("Hour([start_hour])", "TimeQuery", "[id]=" & counter)
    MsgBox (counter)

Next

Debug.Print ("")

但是,如果您想正确执行此操作,请使用记录集

Dim rs As DAO.Recordset
Set rs = CurrentDb.OpenRecordset ("SELECT Hour([start_hour]) As hr FROM TimeQuery WHERE [id] <=3 ORDER BY ID ASC")
Do While Not rs.EOF
   MsgBox rs!hr
   rs.MoveNext
Loop