Search code examples
formsms-accessvbaautonumber

Access VBA: how to get auto numbering on continuous form records


I have a form of view type "continuous forms" that is returning records based on a query, and I want the records to have a number label like 1, 2, 3.. in the order listed:

form

Is there any way to generate a label or textbox automatically there?

Any help is appreciated! Thanks

EDIT: Heres the query code:

    Dim qd As DAO.QueryDef
    Set qd = CurrentDb.CreateQueryDef("pairsOrdered", "select * from allPairs order by Count desc")

    Dim rs As DAO.Recordset
    Set rs = CurrentDb.OpenRecordset("pairsOrdered")
    If Not rs.EOF Then
        Me.Label22.Visible = 0
    End If

    If Me.OpenArgs = "25" Then
        RecordSource = "select top 25 * from pairsOrdered"
    End If

    If Me.OpenArgs = "50" Then
        RecordSource = "select top 50 * from pairsOrdered"
    End If

    If Me.OpenArgs = "all" Then
        RecordSource = "select * from pairsOrdered"
    End If

Solution

  • If your table includes a numeric primary key, you can use DCount() in your query to generate a sequence number. In this example, id is a number and the primary key.

    SELECT DCount("*","MyTable","id<=" & [m].[id]) AS sequence_num, m.id, m.some_text
    FROM MyTable AS m
    ORDER BY DCount("*","MyTable","id<=" & [m].[id]);
    

    You can change the ORDER BY to refer to the field expression's ordinal value in the field list, rather than the full field expression, if you prefer.

    ORDER BY 1;
    

    Either way, the query should produce an editable record source for your form, though obviously you won't be able to edit the sequence_num directly ... so set the properties of the control you bind to it as Enable=No and/or Locked=Yes.

    You could use a subquery instead of the DCount expression for sequence_num, but then you will get a read-only recordset.

    This approach does not require a numeric primary key, but you do need a unique field or combination of fields which is unique. You can also do it with text or date fields.

    Edit: If you delete rows in the form, do Me.Requery in the form's After Update Confirm event. If you add a row which you want displayed before the end of the recordset, do Me.Requery then, too. Same if you edit values in the unique field(s) for existing rows.