Access (VBA) 访问记录集中的最后一条记录

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/27412372/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-12 05:29:28  来源:igfitidea点击:

Access (VBA) accessing the last record in a record set

databasevbaaccess-vbastorerecordset

提问by Connor Stansfield

Trying to get the RecieptNumber (autonumber) from the most recent record in the table 'Invoices' to store the value in the variable invoiceNum (integer).

尝试从“发票”表中的最新记录中获取 RecieptNumber(自动编号),以将值存储在变量 invoiceNum(整数)中。

Dim rstInvoices As Recordset

Set cdCurrentDatabase = CurrentDb
Set rstInvoices = cdCurrentDatabase.OpenRecordset("SELECT LAST ([RecieptNumber]) FROM Invoices;")

invoiceNum = rstInvoices("[RecieptNumber]").Value

Started VBA programming yesterday so appreciate any help that I will be able to understand.

昨天开始了 VBA 编程,所以感谢我能够理解的任何帮助。

回答by

You'll want to do something like:

你会想要做这样的事情:

SELECT TOP 1 RecieptNumber FROM Invoices ORDER BY RecieptNumber DESC

This will order them so the last record is first in the list, and then it takes the first record. Assuming, of course, RecieptNumber is created in numerical order.

这将对它们进行排序,因此最后一条记录在列表中排在第一位,然后是第一条记录。当然,假设 RecieptNumber 是按数字顺序创建的。

And it's bugging me, so I'll add this - it should be ReceiptNumber, not RecieptNumber...

它困扰着我,所以我要添加这个 - 它应该是 ReceiptNumber,而不是 RecieptNumber...

回答by paulroho

The string argument to rstInvoiceshas to refer to a field that is actually returned by executing the Select statement. But the query does not return a field RecieptNumber, but the Last(RecieptNumber)without a specified name. Therefore you first want to give that aggregated column a name using the ASclause:

to 的字符串参数rstInvoices必须引用执行 Select 语句实际返回的字段。但是查询不返回 field RecieptNumber,而是返回Last(RecieptNumber)没有指定名称的。因此,您首先要使用以下AS子句为该聚合列命名:

SELECT LAST(RecieptNumber) AS LastNumber ...

Now you can refer to that field in VBA:

现在您可以在 VBA 中引用该字段:

invoiceNum = rstInvoices("[LastNumber]").Value