开发者

how do i determine what the next record number (PK) is?

im trying to get the next number in the autonumber sequence for the primary key programatically. For instance, if the last number in the table was 10, i need it to return 11. Before, I would use something like:

docmd.RunCommand acCmdRecordsGoToNew

in order to tell the database to go to the next record, and then i'd assign it to a control on the form to开发者_JAVA技巧 show the user what record they are currently entering. The problem is, this function ceased to work when I disabled the navigation buttons by setting it's property to "No" in the properties window. How do I get the next record in vba without the nav bar being enabled?


To know what the real next value is, you have to look up the SeedValue for your Autonumber column. This code does that:

  Public Function GetSeedValue(strTable As String, strColumn As String) As Long
    Dim cnn As Object 'ADODB.Connection
    Dim cat As Object ' New ADOX.Catalog
    Dim col As Object ' ADOX.Column

    Set cnn = CurrentProject.Connection
    Set cat = CreateObject("ADOX.Catalog")
    cat.ActiveConnection = cnn

    Set col = cat.Tables(strTable).Columns(strColumn)
    GetSeedValue = col.Properties("Seed")

    Set col = Nothing
    Set cat = Nothing
    Set cnn = Nothing
  End Function

If you're going to call it a lot, you'd likely want to cache the ADOX Catalog object variable, rather than re-initialize it each time you call this function.

Note that in a multiuser environment, this may or may not be accurate, since by the time you use it, it may have been updated by another user. However, it doesn't have the problem with skipping Autonumber values that Max()+1 can have.

Keep in mind, though, that if you care about the next Autonumber value, it means YOU'RE USING IT WRONG. Autonumber values are surrogate keys and you should never, ever care what the values are.


Turns out that there is a VBA function that will interact with the database and actually return a value. This is what I ended up doing to get the next record number:

Dim nextRecord As Integer
nextRecord = DMax("ID", "my_table") + 1

Sloppy, but effective for my single client situation. There is also a where clause that can be applied:

Dim nextRecord As Integer
nextRecord = DMax("ID", "my_table", "field =  value")
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜