How to get id of newly inserted record using Excel VBA?

前端 未结 6 1598
傲寒
傲寒 2020-12-16 20:49

Seems a common enough problem this, but most solutions refer to concatenating multiple SQL commands, something which I believe can\'t be done with ADO/VBA (I\'ll be glad to

6条回答
  •  自闭症患者
    2020-12-16 21:06

    If the artificial key is an autonumber, you can use @@identity.

    Note that with both these examples, the transaction is isolated from other events, so the identity returned is the one just inserted. You can test this by pausing the code at Debug.Print db.RecordsAffected or Debug.Print lngRecs and inserting a record manually into Table1, continue the code and note that the identity returned is not that of the record inserted manually, but of the previous record inserted by code.

    DAO Example

    'Reference: Microsoft DAO 3.6 Object Library '
    Dim db As DAO.Database
    Dim rs As DAO.Recordset
    
    Set db = CurrentDb
    
    db.Execute ("INSERT INTO table1 (field1, Crdate ) " _
                & "VALUES ( 46, #" & Format(Date, "yyyy/mm/dd") & "#)")
    Debug.Print db.RecordsAffected
    Set rs = db.OpenRecordset("SELECT @@identity AS NewID FROM table1")
    Debug.Print rs.Fields("NewID")
    

    ADO Example

    Dim cn As New ADODB.Connection
    Dim rs As New ADODB.Recordset
    
    Set cn = CurrentProject.Connection
    
    cn.Execute ("INSERT INTO table1 (field1, Crdate ) " _
                & "VALUES ( 46, #" & Format(Date, "yyyy/mm/dd") & "#)"), lngRecs
    Debug.Print lngRecs
    rs.Open "SELECT @@identity AS NewID FROM table1", cn
    Debug.Print rs.Fields("NewID")
    

提交回复
热议问题