(VBA)用于循环和DLookup (MS ACCESS)

时间:2022-05-08 15:38:12

I have a query named TimeQuery. I want MsgBox will show all [start_hour] values where [id]=1 then 2 etc. ... I have a problem. When i will use:

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

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

it works good, but when use [id]=counter it doesn't show it. I have a MsgBox after that For Loop too and when [id]=counter it doesn't show that MsgBox too. What's wrong?

它工作得很好,但是当使用[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 ("")

1 个解决方案

#1


2  

You need to concatenate your variable to a string if you want to use this, like so:

如果你想要使用这个,你需要将你的变量连接到一个字符串,如下所示:

For counter = 1 To 3
    Dim a As Variant

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

Next

Debug.Print ("")

However, if you want to do this properly, use recordsets

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

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

#1


2  

You need to concatenate your variable to a string if you want to use this, like so:

如果你想要使用这个,你需要将你的变量连接到一个字符串,如下所示:

For counter = 1 To 3
    Dim a As Variant

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

Next

Debug.Print ("")

However, if you want to do this properly, use recordsets

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

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