如何从访问表中查找下一个ID自动编号并在Excel用户表单中显示该编号?

时间:2020-06-11 14:52:19

标签: excel vba ms-access userform autonumber

我想从访问表中获取下一个ID自动编号,并将其显示在excel用户窗体上的文本框中。我已经找到了这段代码,并且已经使用了它,但是我什么也没走,而且完全迷路了。如果有人能指出正确的方向解决我,我将不胜感激。

    Dim con As Object: Set con = CreateObject("ADODB.Connection")
    Dim rs As Object: Set rs = CreateObject("ADODB.Recordset")
    Dim sql As String

    connectionstring = "PROVIDER=Microsoft.ACE.OLEDB.12.0;"
    connectionstring = connectionstring & "DATA Source=C:\Users\MyPc\Desktop\Database1.accdb;"
    con.Open connectionstring

    sql = "select max(ID) as maxvalue from TableOne"

    con.Execute sql

    NextValue = (maxvalue) + 1

     MsgBox NextValue
     userform1.textbox2.value = NextValue
     rs.Close
     Set rs = Nothing

1 个答案:

答案 0 :(得分:2)

执行是针对操作SQL(INSERT,UPDATE,DELETE)而不是SELECT的。使用SELECT打开一个记录集对象,然后从记录集中读取数据。

    Dim con As Object: Set con = CreateObject("ADODB.Connection")
    Dim rs As Object: Set rs = CreateObject("ADODB.Recordset")
    Dim sql As String

    connectionstring = "PROVIDER=Microsoft.ACE.OLEDB.12.0;"
    connectionstring = connectionstring & "DATA Source=C:\Users\MyPc\Desktop\Database1.accdb;"
    con.Open connectionstring

    sql = "select max(ID) as maxvalue from TableOne"

    rs.Open sql, con, adOpenStatic, adLockReadOnly 

    NextValue = (rs!maxvalue) + 1

    MsgBox NextValue
    userform1.textbox2.value = NextValue
    rs.Close
    Set rs = Nothing

由于只需要一个值,请考虑选择:

Dim appAccess As Object
Set appAccess = CreateObject("Access.Application")
appAccess.OpenCurrentDatabase ("C:\Users\MyPc\Desktop\Database1Umpires.accdb")
userform1.textbox2.value = appAccess.DMax("ID", "TableOne")