捕获主键值

时间:2012-04-23 18:57:52

标签: vba ms-access access-vba

我正在使用以下代码向表中添加记录:

Dim rs1 As DAO.Recordset
Set rs1 = CurrentDb.OpenRecordset("QUOTE-Run", dbOpenDynaset)

rs1.AddNew
rs1.Fields("[QuoteNumber]").value = [txtQuoteNumber].value
rs1.Fields("[LeadTime]").value = [txtLeadTime].value
rs1.Fields("[Qty]").value = [txtQty].value
rs1.Fields("[Title]").value = [txtTitle].value
rs1.Fields("[Date]").value = VBA.DateTime.Date
rs1.Fields("[Time]").value = VBA.DateTime.Time
rs1.Fields("[InitiatedBy]").value = Application.CurrentUser
rs1.Fields("[IncompleteProblemNotes]").value = [txtIncompleteProblemNotes].value
rs1.Fields("[CustomerNotes]").value = [txtCustomerNotes].value
rs1.Fields("[Memo]").value = [txtMemo].value
rs1.Fields("[Memo1]").value = [txtMemo1].value
rs1.Fields("[PrefferedQuoteRunSelect]").value = [txtPrefferedQuoteRunSelect].value
rs1.Fields("[CombinedRun]").value = [chkCombinedRun].value
rs1.Update

创建记录时,会有一个名为RunID的AutoNumber主键字段获取值。我需要知道这个值是什么,所以我可以在以后的代码中使用它。捕获该值的最简单方法是什么?

2 个答案:

答案 0 :(得分:3)

我能想到让你获得RunID值的最简单方法是声明一个变量并在更新记录之前将该变量设置为等于该字段。像这样:

   Dim rs1 As DAO.Recordset
   Set rs1 = CurrentDb.OpenRecordset("QUOTE-Run", dbOpenDynaset)
   Dim TempRunID As Long

   rs1.AddNew
   rs1.Fields("[QuoteNumber]").value = [txtQuoteNumber].value
   rs1.Fields("[LeadTime]").value = [txtLeadTime].value
   rs1.Fields("[Qty]").value = [txtQty].value
   rs1.Fields("[Title]").value = [txtTitle].value
   rs1.Fields("[Date]").value = VBA.DateTime.Date
   rs1.Fields("[Time]").value = VBA.DateTime.Time
   rs1.Fields("[InitiatedBy]").value = Application.CurrentUser
   rs1.Fields("[IncompleteProblemNotes]").value = [txtIncompleteProblemNotes].value
   rs1.Fields("[CustomerNotes]").value = [txtCustomerNotes].value
   rs1.Fields("[Memo]").value = [txtMemo].value
   rs1.Fields("[Memo1]").value = [txtMemo1].value
   rs1.Fields("[PrefferedQuoteRunSelect]").value = [txtPrefferedQuoteRunSelect].value
   rs1.Fields("[CombinedRun]").value = [chkCombinedRun].value

   TempRunID = rs1.Fields("[RunID]").value
   rs1.Update

答案 1 :(得分:1)

您可以运行第二个使用函数

的查询
SELECT LAST_INSERT_ID();