How to add sequential numbers next to data from query

不问归期 提交于 2021-02-05 09:23:44

问题


I have a table named tblFriends:

tblFriends is generated from query qryFriends. The data and number of records within tblFriends changes everyday but is never more than 30.

I would like to generate sequential numbers next to each of the Names, but this seems to be extremely difficult.

I have tried looping insert queries as shown below:

strSQLaddSEQ = "ALTER TABLE tblFriends ADD SEQ Number;"
DoCmd.RunSQL strSQLaddSEQ

For SEQNum = 1 To 30

   strSqlSEQNum = "INSERT INTO Friends (SEQ) Values(" & SEQNum & ");"
   DoCmd.RunSQL strSqlSEQNum

Next SEQNum

This always results in my SEQ numbers showing up below the data even though it's a newly created field.

How do I simply add sequence numbers from 1-30 next to my data? Or at the very least how do I add a sequence number for the data I have?

(Maybe?)Is there a way to maybe loop through each row(row by row) copying to a new table then creating a SEQ number there and repeating 30 times? I don't care even if I need to do this field by field row by row.

For example, I'm ok if I need to simply go:

1 - Bikes
2 - Food
3 - Money
4 - Shoes
5 - Computers 
6 - Clothes
7 - Soda 

But how do I go row by row like that and maintain sequence order I had from the start? Is there a looping process?

The initial record sequence is important and needs to be maintained.


回答1:


I think I figured out the solution to my own question...but I haven't tested it yet since I'm home now and don't have my work computer.

Assume I've created a table named tblSeqNames with fields "Names” and "SEQ".

Dim rs As Recordset

Dim strNames As String

Set rs = CurrentDb.OpenRecordset("qryFriends", dbOpenDynaset, dbSeeChanges)

strSQL = "INSERT INTO tblSeqNames (Names, SEQ) VALUES ('" & strNames & "', " & SEQNum & ")"

For SEQNum = 1 To 30

    strNames = rs.Fields("Name").Value

        DoCmd.RunSQL strSQL

    rs.MoveNext

Next SEQNum



回答2:


You can have an external function which you pass the form as an argument.

It's very simple to implement. Study the in-line comments:

' Creates and returns a sequential record number for records displayed
' in a form, even if no primary or unique key is present.
' For a new record, Null is returned until the record is saved.
'
' Implementation, typical:
'
'   Create a TextBox to display the record number.
'   Set the ControlSource of this to:
'
'       =RecordNumber([Form])
'
'   The returned number will equal the Current Record displayed in the
'   form's record navigator (bottom-left).
'   Optionally, specify another first number than 1, say, 0:
'
'       =RecordNumber([Form],0)
'
'   NB: For localised versions of Access, when entering the expression, type
'
'       =RecordNumber([LocalisedNameOfObjectForm])
'
'   for example:
'
'       =RecordNumber([Formular])
'
'   and press Enter. The expression will update to:
'
'       =RecordNumber([Form])
'
'   If the form can delete records, insert this code line in the
'   AfterDelConfirm event:
'
'       Private Sub Form_AfterDelConfirm(Status As Integer)
'           Me!RecordNumber.Requery
'       End Sub
'
'   If the form can add records, insert this code line in the
'   AfterInsert event:
'
'       Private Sub Form_AfterInsert()
'           Me!RecordNumber.Requery
'       End Sub
'
' Implementation, stand-alone:
'
'   Dim Number As Variant
'
'   Number = RecordNumber(Forms(IndexOfFormInFormsCollection))
'   ' or
'   Number = RecordNumber(Forms("NameOfSomeOpenForm"))
'
'
' 2018-09-14. Gustav Brock, Cactus Data ApS, CPH.
'
Public Function RecordNumber( _
    ByRef Form As Access.Form, _
    Optional ByVal FirstNumber As Long = 1) _
    As Variant

    ' Error code for "There is no current record."
    Const NoCurrentRecord   As Long = 3021
    
    Dim Records             As DAO.Recordset
    
    Dim Number              As Variant
    Dim Prompt              As String
    Dim Buttons             As VbMsgBoxStyle
    Dim Title               As String

    On Error GoTo Err_RecordNumber
    If Form Is Nothing Then
        ' No form object is passed.
        Number = Null
    ElseIf Form.Dirty = True Then
        ' No record number until the record is saved.
        Number = Null
    ElseIf Form.NewRecord = True Then
        ' No record number on a new record.
        Number = Null
    Else
        Set Records = Form.RecordsetClone
        Records.Bookmark = Form.Bookmark
        Number = FirstNumber + Records.AbsolutePosition
        Set Records = Nothing
    End If
    
Exit_RecordNumber:
    RecordNumber = Number
    Exit Function
    
Err_RecordNumber:
    Select Case Err.Number
        Case NoCurrentRecord
            ' Form is at new record, thus no Bookmark exists.
            ' Ignore and continue.
        Case Else
            ' Unexpected error.
            Prompt = "Error " & Err.Number & ": " & Err.Description
            Buttons = vbCritical + vbOKOnly
            Title = Form.Name
            MsgBox Prompt, Buttons, Title
    End Select
    
    ' Return Null for any error.
    Number = Null
    Resume Exit_RecordNumber

End Function

It is part of my project VBA.RowNumbers where you will find a lot of other methods to enumerate rows, each with some advanteges and disadvantages.



来源:https://stackoverflow.com/questions/62525466/how-to-add-sequential-numbers-next-to-data-from-query

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!