Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
653 views
in Technique[技术] by (71.8m points)

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

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

Location Number
-------- ------
ABC      1
DEF      1
DEF      2
GHI      1
ABC      2
ABC      3

Every time I append data to the table I would like the number to be unique to the location. I am accessing this table through MS Excel VBA - I would like to create a new record (I specify the location in the code) and have a unique sequential number created. Is there a way to setup the table so this happens autmatically when a record is added? Should I write a query of some description and to determine the next number per location, and then specify both the Location & Number when I create the record?

I am writing to the table as below:

    Set rst = New ADODB.Recordset
    rst.CursorLocation = adUseServer
    rst.Open Source:="Articles", _
         ActiveConnection:=cnn, _
         CursorType:=adOpenDynamic, _
         LockType:=adLockOptimistic, _
         Options:=adCmdTable
    rst.AddNew
    rst("Location") = fLabel.Location 'fLabel is an object contained within a collection called manifest
    rst("Number") = 'Determine Unique number per location
    rst.Update

Any help would be appreciated.

Edit - Added the VBA code I am struggling with as question was put on-hold

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...