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

前端 未结 6 1606
傲寒
傲寒 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:13

    Here's my solution that does not use @@index or MAX.

    Const connectionString = "Provider=SQLOLEDB; Data Source=SomeSource; Initial Catalog=SomeDB; User Id=YouIDHere; Password=YourPassword"
    Const RecordsSQL = "SELECT * FROM ThatOneTable"
    
    Private Sub InsertRecordAndGetID()
        Set connection = New ADODB.connection
        connection.connectionString = connectionString
        connection.Open
        Set recordset = New ADODB.recordset
        recordset.Open SQL, connection, adOpenKeyset, adLockOptimistic
    
        With recordset
            .AddNew
            !Field1 = Value1
            !Field2 = Value2
        End With
    
        recordset.MoveLast
        ID = recordset.Fields("id")
    
    End Sub
    

    Enjoy!

提交回复
热议问题