2014-12-10 133 views
0

嘗試從表'發票'中的最近記錄獲取RecieptNumber(autonumber)以將值存儲在變量invoiceNum(integer)中。訪問(VBA)訪問記錄集中的最後一條記錄

Dim rstInvoices As Recordset 

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

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

昨天開始VBA編程,非常感謝任何幫助,我將能夠理解。

+0

您的要求:'SELECT LAST([RecieptNumber])如rNum FROM Invoices'您的vba:'InvoicesinvoiceNum = rstInvoices.Fields(「rNum」)。Value'。另請參閱:http://msdn.microsoft.com/fr-fr/library/office/ff197799(v=office.15).aspx – scraaappy 2014-12-10 22:57:49

+0

[如何獲取表單的最後一條記錄ID?]( http://stackoverflow.com/questions/13587638/how-to-get-the-last-record-id-of-a-form) – LondonRob 2014-12-10 23:02:28

+0

如果你在一個多用戶系統上,任何涉及Last,Top等的東西,是非常危險的,你需要一個CurrentDb和@@ Identity的實例,參見http://stackoverflow.com/questions/1628267/autonumber-value-of-last-inserted-row-ms-access-vba – Fionnuala 2014-12-11 01:28:33

回答

0

的字符串參數rstInvoices有提及,實際上是通過執行SELECT語句返回現場。但是查詢不返回字段RecieptNumber,但是Last(RecieptNumber)沒有指定名稱。因此,你首先要使用AS條款,得到聚合列名:

SELECT LAST(RecieptNumber) AS LastNumber ... 

現在,您可以參考該字段中VBA:

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

你想要做的事,如:

SELECT TOP 1 RecieptNumber FROM Invoices ORDER BY RecieptNumber DESC 

這將責令其所以最後一個記錄是第一個在列表中,然後它需要的第一個記錄。當然,假定RecieptNumber按數字順序創建。

而且它的竊聽我,所以我會補充這一點 - 它應該是ReceiptNumber,不RecieptNumber ...