Generate a sequential number (per group) when adding a row to an Access table

前端 未结 3 1188
悲&欢浪女
悲&欢浪女 2021-01-07 10:45

I have an MS Access (.accdb) table with data like the following:

Location Number
-------- ------
ABC      1
DEF              


        
相关标签:
3条回答
  • 2021-01-07 11:05

    For Access 2010 and newer, this is a better way to do it. It uses the table's Before Change Data Macro to derive the next sequential number and put it in the [Number] field of the new record:

    BeforeChange.png

    The advantages of this approach are:

    • The sequence number will be applied whenever a new record is added, regardless of how it is added.
    • The Excel VBA code does not have to worry about creating the sequence number; it "just happens".
    • Since this code resides at the table level it should be safe for a multi-user environment.

    For more information on Data Macros, see

    Create a data macro

    0 讨论(0)
  • 2021-01-07 11:07

    You need to add a new column to your table of data type AutoNumber.

    office.microsoft.com: Fields that generate numbers automatically in Access

    You should probably also set this column as your primary key.

    0 讨论(0)
  • 2021-01-07 11:13

    I suspect that you are looking for something like this:

    Dim con As ADODB.Connection, cmd As ADODB.Command, rst As ADODB.Recordset
    Dim newNum As Variant
    
    Const fLabel_Location = "O'Hare"  ' test data
    
    Set con = New ADODB.Connection
    con.Open "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:\Users\Public\Database1.accdb;"
    
    Set cmd = New ADODB.Command
    cmd.ActiveConnection = con
    cmd.CommandText = "SELECT MAX(Number) AS maxNum FROM Articles WHERE Location = ?"
    cmd.CreateParameter "?", adVarWChar, adParamInput, 255
    cmd.Parameters(0).Value = fLabel_Location
    Set rst = cmd.Execute
    newNum = IIf(IsNull(rst("maxNum").Value), 0, rst("maxNum").Value) + 1
    rst.Close
    
    rst.Open "Articles", con, adOpenDynamic, adLockOptimistic, adCmdTable
    rst.AddNew
    rst("Location").Value = fLabel_Location
    rst("Number").Value = newNum
    rst.Update
    rst.Close
    Set rst = Nothing
    Set cmd = Nothing
    con.Close
    Set con = Nothing
    

    Note, however, that this code is not multiuser-safe. If there is the possibility of more than one user running this code at the same time then you could wind up with duplicate [Number] values.

    (To make the code multiuser-safe you would need to create a unique index on ([Location], [Number]) and add some error trapping in case the rst.Update fails.)

    Edit

    For Access 2010 and later consider using an event-driven Data Macro and shown in my other answer to this question.

    0 讨论(0)
提交回复
热议问题