简体   繁体   中英

How to query Microsoft Access Database fields from VBA in Excel

I am currently writing a program to save stuff entered in a form in Excel into a database in Access. I am trying to increment a primary key field within Access by "1" whenever I add data from the fields in my Excel form.

Because I have declared this field as a PRIMARY KEY NOT NULL field, it doesn't allow me add another row of data unless the primary key field has been declared. I do not want the user to enter the PK data, as that would be silly.

How would I go about doing DDL from Excel into Access like say MAX(CustomerID) to find the maximum ID wihtin the Access table then adding MAX(CustomerID) + 1 into the ID field using RS.FIELD("CustomerID") = MAX(CustomerID) + 1 .

I would be grateful for any help in this matter. Thanks in advance.

You can declare a column as Autoincrement in Access. Then it will get subsequent values automatically.

I like the idea of using an AutoNumber field as suggested in other answers.

However if you wish to steer clear of AutoNumber you can use Access's DLookup function from your VBA in Excel:

rs.AddNew
rs.Fields("CustomerID") = Access.DLookup("Max(CustomerID)", "Customer") + 1

...

rs.Update

Assuming your base table is Customer .

You would have to add the reference to Microsoft Access in Tools->References

Would it not be possible to create the form in access itself and then you can just use the auto number field of the database? Unless there is a specific reason to keep it in excel it seems like a bit of a convoluted solution to the problem

If you don't want to use the above DLookup function, you can also create a VBA function to retrieve the value for you, then embed this in your insert into.

Private Function GetNextPKID(MyConnectionString) as Integer
dim rs as adodb.recordset, cn as adodb.connection, sSQL as string

sSQL = "SELECT COUNT(*) FROM MyTable"

set cn = new adodb.connection
set rs = new adodb.recordset
cn.ConnectionString = MyConnectionString
cn.Open
set rs.ActiveConnection = cn
rs.Open(sSQL)

GetNextPKID = rs.Fields(0).Value + 1

cn.Close
set cn = nothing
set rs = nothing
End Function

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM