简体   繁体   English

如何从Excel中的VBA查询Microsoft Access数据库字段

[英]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. 我目前正在编写一个程序,以将在Excel表单中输入的内容保存到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. 每当我从Excel表单中的字段添加数据时,我都试图将Access中的主键字段增加“ 1”。

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. 因为我已经将该字段声明为PRIMARY KEY NOT NULL字段,所以除非声明了主键字段,否则它不允许我添加另一行数据。 I do not want the user to enter the PK data, as that would be silly. 我不希望用户输入PK数据,因为那样很愚蠢。

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 . 我怎么会去从Excel做DDL到像访问说MAX(CustomerID)找到wihtin Access表然后加入最大ID MAX(CustomerID) + 1使用到ID字段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. 您可以在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: 但是,如果您希望避免使用自动编号,则可以从Excel中的VBA使用Access的DLookup函数:

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

...

rs.Update

Assuming your base table is Customer . 假设您的基本表是Customer

You would have to add the reference to Microsoft Access in Tools->References 您必须在“工具”->“引用”中添加对Microsoft Access的引用

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 除非有特定的原因使它保持在excel中,否则似乎有点麻烦了

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. 如果您不想使用上面的DLookup函数,则还可以创建一个VBA函数来为您检索值,然后将其嵌入到您的插入对象中。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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