access调整字段顺序

This is the second article on row numbers in Microsoft Access.

这是有关Microsoft Access中行号的第二篇文章。

The first is about Random Rows in Microsoft Access.

首先是关于Microsoft Access中的随机行

The third is about Ranking rows in Microsoft Access.

第三是关于在Microsoft Access中对行进行排名 。

(
)

这是为了什么 (What is it for?)

Typically, the reason for assigning a sequential number to each record of a recordset is one of these:

通常,为记录集的每个记录分配顺序号的原因是以下之一:

  • to add a sequential number to records where no other simple ID is present在没有其他简单ID的记录中添加序号
  • to enumerate and count the rows returned from a query or listed in a form枚举并计算从查询返回或以表格形式列出的行
  • to view or control the position of specific records查看或控制特定记录的位置
  • to add a unique ID or a kind of serial number to records before an export在导出之前在记录中添加唯一的ID或一种序列号

That can, in some cases, be obtained with no code other than a simple expression, while other cases may require a more robust or resistant method where code must be used. For this reason, three methods will be discussed here:

在某些情况下,仅使用简单的表达式就可以不使用任何代码而获得代码,而在其他情况下,可能需要使用必须使用代码的更健壮或更具抵抗性的方法。 因此,这里将讨论三种方法:

  1. Add a sequential record number to each row in a form在表格的每一行中添加一个顺序记录号
  2. Add a sequential row number to each record of a query在查询的每个记录中添加顺序行号
  3. Add a sequential user maintained priority number to each record in a form向表单中的每个记录添加一个顺序的用户维护的优先级编号

Each method has some distinct advantages and (perhaps) disadvantages that must be taken into consideration before deciding which method to use in a given scenario.

每种方法都有一些明显的优点和(也许)缺点,在决定在给定方案中使用哪种方法之前,必须考虑这些优点和缺点。

1.记录编号 (1. Record Numbers)

These are similar to the Record Number displayed in the Navigation Bar of a form (left-bottom, in the status bar of the form).

这些类似于在表单的导航栏中显示的记录编号(在表单的状态栏中为左下)。

优点 (Advantages)

  • Will always be sequential from top to bottom of the form, no matter how records are ordered, filtered, edited, deleted, or inserted无论记录如何排序,过滤,编辑,删除或插入,它将始终从表格的顶部到底部是连续的
  • For a form, the source can be a table; a query is not required对于表单,源可以是表格; 不需要查询

缺点 (Disadvantages)

  • Will not, for the individual record, be static ("sticky")对于个人记录,不会是静态的(“粘性”)
  • Belongs to the form, not the recordset属于表格,而不是记录集
  • May update slowly when browsing the form浏览表单时可能更新缓慢
  • For forms only, not queries仅用于表单,不用于查询

实作 (Implementation)

The function for this is passed the form itself as a parameter, then uses the RecordsetClone of the form to obtain the AbsolutPosition of the record, which always indicates where the record currently is positioned in the form.

为此的函数将表单本身作为参数传递,然后使用表单的RecordsetClone获得记录的AbsolutPosition ,该位置始终指示当前在表单中放置记录的位置。

' 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.
'
' 2018-08-23. 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
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

The implementation in the form is extremely simple:

形式的实现非常简单:

Create a TextBox to display the record number, and set the ControlSource of this to:

创建一个TextBox以显示记录号,并将其ControlSource设置为:

=RecordNumber([Form])

The returned number will equal the Current Record displayed in the form's record navigator (bottom-left).

返回的数字将等于窗体的记录导航器(左下)中显示的“当前记录”。

Optionally, you may specify a first number other than 1, say 0, by using the second parameter:

(可选)您可以使用第二个参数指定除1以外的第一个数字,例如0:

=RecordNumber([Form],0)

NB: For localised versions of Access, when entering the expression, type:

注意:对于Access的本地化版本,在输入表达式时,键入:

=RecordNumber([LocalisedNameOfObjectForm])

for example:

例如:

=RecordNumber([Formular])

and press Enter. The expression will update to:

然后按Enter。 该表达式将更新为:

=RecordNumber([Form])

If the form can't add or delete records, you're done, but if it is, you will have to requery the textbox to update the numbers:

如果表单无法添加或删除记录,则说明您已经完成,但是如果是,则必须重新查询文本框以更新数字:

Private Sub Form_AfterDelConfirm(Status As Integer)
Me!RecordNumber.Requery
End Sub
Private Sub Form_AfterInsert()
Me!RecordNumber.Requery
End Sub

其他用法 (Other usage)

You may also use the function from elsewhere to obtain the record number of an open form:

您还可以从其他地方使用该函数来获取打开表格的记录号:

Dim Number As Variant
Number = RecordNumber(Forms(IndexOfSomeFormInFormsCollection))
' or
Number = RecordNumber(Forms("NameOfSomeOpenForm")

2.行号 (2. Row Numbers)

These are created in a query, as a separate field of the resulting recordset.

这些在查询中创建,作为结果记录集的单独字段。

优点 (Advantages)

  • The numbers will not update if records are deleted, and new records will be assigned the next higher number(s) as long as the query is not required如果删除记录,则编号不会更新,并且只要不需要查询,就会为新记录分配下一个更高的编号。
  • The numbers will be defined by the ordering of the query数字将通过查询的顺序定义
  • If a form is bound to the query, the numbers will always stick to the individual record, no matter how the form is ordered or filtered, or (if the query or form is not updated/required) if records are added or deleted如果将表格绑定到查询,则无论表格如何排序或过滤,或者(如果查询或表格未更新/不需要)是否添加或删除了记录,数字始终会粘贴在单个记录上
  • Generating the numbers takes one table scan only, thus browsing the query, or a form bound to it is very fast生成数字仅需进行一次表扫描 ,因此浏览查询或与其绑定的表格非常快
  • As the numbers are static ("sticky"), they are well suited for export or for use in append queries由于数字是静态的(“粘性”),因此非常适合导出或在附加查询中使用

缺点 (Disadvantages)

  • If records are added or deleted, the assigned numbers may change after a re-query to maintain sequentiality如果添加或删除记录,则重新查询后分配的编号可能会更改以保持顺序
  • If used in a form, and different filtering or sorting is applied, there is no method to regain sequentiality other than to revert to the original ordering and remove filtering如果以某种形式使用,并且应用了不同的过滤或排序,则除了恢复到原始顺序并删除过滤之外,没有其他方法可以恢复顺序

实作 (Implementation)

The function to create the row numbers uses a collection to store these. The great advantage of this method is, that it only takes one table scan to calculate and store the numbers. From then on, the numbers are read directly from the collection, which is very fast. Thus, a query or form displaying the row numbers is not degraded when browsed or read multiple times.

创建行号的功能使用一个集合来存储它们。 该方法的最大优点是,只需进行一次表扫描即可计算和存储数字。 从那时起,可以直接从集合中读取数字,这非常快。 因此,当多次浏览或读取时,显示行号的查询或表单不会降级。

In addition to the traditional numbering of the full recordset, the function also offers numbering of groups and numbering of records on the group level. This is quite fancy and a bit hard to explain without studying the code line by line, thus extensive in-line comments that explain every step has been included in the function for those interested.

除了对完整记录集进行传统编号之外,该功能还提供组编号和组级别上的记录编号。 如果不逐行研究代码,这是相当花哨的,并且很难解释,因此,对于那些感兴趣的人,在函数中包含了解释每一步的大量内联注释。

' Builds consecutive row numbers in a select, append, or create query
' with the option of a initial automatic reset.
' Optionally, a grouping key can be passed to reset the row count
' for every group key.
'
' 2018-08-23. Gustav Brock, Cactus Data ApS, CPH.
'
Public Function RowNumber( _
ByVal Key As String, _
Optional ByVal GroupKey As String, _
Optional ByVal Reset As Boolean) _
As Long
' Uncommon character string to assemble GroupKey and Key as a compound key.
Const KeySeparator      As String = "¤§¤"
' Expected error codes to accept.
Const CannotAddKey      As Long = 457
Const CannotRemoveKey   As Long = 5
Static Keys             As New Collection
Static GroupKeys        As New Collection
Dim Count               As Long
Dim CompoundKey         As String
On Error GoTo Err_RowNumber
If Reset = True Then
' Erase the collection of keys and group key counts.
Set Keys = Nothing
Set GroupKeys = Nothing
Else
' Create a compound key to uniquely identify GroupKey and its Key.
' Note: If GroupKey is not used, only one element will be added.
CompoundKey = GroupKey & KeySeparator & Key
Count = Keys(CompoundKey)
If Count = 0 Then
' This record has not been enumerated.
'
' Will either fail if the group key is new, leaving Count as zero,
' or retrieve the count of already enumerated records with this group key.
Count = GroupKeys(GroupKey) + 1
If Count > 0 Then
' The group key has been recorded.
' Remove it to allow it to be recreated holding the new count.
GroupKeys.Remove (GroupKey)
Else
' This record is the first having this group key.
' Thus, the count is 1.
Count = 1
End If
' (Re)create the group key item with the value of the count of keys.
GroupKeys.Add Count, GroupKey
End If
' Add the key and its enumeration.
' This will be:
'   Using no group key: Relative to the full recordset.
'   Using a group key:  Relative to the group key.
' Will fail if the key already has been created.
Keys.Add Count, CompoundKey
End If
' Return the key value as this is the row counter.
RowNumber = Count
Exit_RowNumber:
Exit Function
Err_RowNumber:
Select Case Err
Case CannotAddKey
' Key is present, thus cannot be added again.
Resume Next
Case CannotRemoveKey
' GroupKey is not present, thus cannot be removed.
Resume Next
Case Else
' Some other error. Ignore.
Resume Exit_RowNumber
End Select
End Function

The typical usage in a select query is:

选择查询的典型用法是:

SELECT RowNumber(CStr([ID])) AS RowID, *
FROM SomeTable
WHERE (RowNumber(CStr([ID])) <> RowNumber("","",True));

If the table has no index, it will be slightly different:

如果表没有索引,则将略有不同:

SELECT RowNumber(CStr([ID])) AS RowID, *
FROM SomeTable
WHERE (RowNumber("","",True)=0);

The purpose of the WHERE clause is to call the function

WHERE子句的目的是调用该函数

once and 一次once onlyfor a reset of the numbers. 一次仅用于重置号码。

As the call of the function to create a number contains the ID of the record, it will happen for each record, but the call for a reset does not, thus the query will call it first - and once only.

由于创建数字的函数的调用包含记录的ID,因此每条记录都会发生该调用,但是重置不会发生,因此查询将首先调用它,并且仅调用一次。

If you need to include a group key, it is easily done - just specify it as the second parameter:

如果您需要包括一个组密钥 ,则很容易完成-只需将其指定为第二个参数即可:

SELECT RowNumber(CStr([ID]), CStr[GroupID])) AS RowID, *
FROM SomeTable
WHERE (RowNumber(CStr([ID])) <> RowNumber("","",True));

If you wish to create an append query, a similar technique can be used:

如果您希望创建一个追加查询 ,可以使用类似的技术:

INSERT INTO TempTable ( [RowID] )
SELECT RowNumber(CStr([ID])) AS RowID, *
FROM SomeTable
WHERE (RowNumber("","",True)=0);

However, it will not always be feasible with an automatic reset. For example: If you wish to run the query several times, every time appending new records, and these records should be assigned one sequential series of numbers, the rest of the row numbers must be done manually.

但是,使用自动复位并不总是可行的。 例如:如果您希望多次运行查询,每次附加新记录,并且这些记录应分配一个连续的数字序列,则其余的行号必须手动完成。

So, first call the function this way to reset the counters:

因此,首先以这种方式调用函数以重置计数器:

RowNumber(vbNullString, , True)

Then run the append query - without a row number reset - as many times as needed:

然后根据需要运行追加查询-无需重置行号-多次:

INSERT INTO TempTable ( [RowID] )
SELECT RowNumber(CStr([ID])) AS RowID, *
FROM SomeTable;

其他用法 (Other usage)

Though only intended for usage as shown in a query - opened either on its own or as the source for a form - the function can also be called from code. Say, you have a query or form open, you can easily look up the assigned row number for any ID of the recordset:

尽管仅用于查询中的用法(可以单独打开或作为表单的源打开),但也可以从代码中调用该函数。 假设您打开了一个查询或表单,则可以轻松查找记录集的任何ID的已分配行号:

Dim Key As String
Key = CStr(IdToLookUp)
AssignedRowNumber = RowNumber(Key)

3.优先号码 (3. Priority Numbers)

The purpose of assigning a priority (or rank) is to define a sort order for a list of records - different from any other possible sort order of the recordset. Typically, this will reflect a decision made by a human (a user), for example for scenarios like these:

分配优先级(或等级)的目的是为记录列表定义排序顺序-与记录集的任何其他可能的排序顺序不同。 通常,这将反映人类(用户)的决定,例如针对以下情况:

  • Order a list of order lines in an order - different from product numbers or the like订购订单中的订单行列表-与产品编号等不同
  • Rank persons等级人员
  • Assign priority to tasks为任务分配优先级
  • Order steps of a checklist清单的订购步骤
  • Order of options for answers to a question in a multiple-choice test多项选择题中对问题答案的选项顺序

The assigned priority is stored in a separate numeric field of the table. Thus, they are persistent, and primarily intended to be maintained by a user having the records listed in a form.

分配的优先级存储在表的单独数字字段中。 因此,它们是持久的,并且主要旨在由具有以表格形式列出的记录的用户来维护。

The task for the function published here is to keep the full series of priorities in sequence when any of these is adjusted. This means, that if a number is changed, other numbers must be increased or decreased to maintain the continuous sequence of numbers.

此处发布的功能的任务是在调整优先级中的任何优先级时保持其顺序。 这意味着,如果更改了数字,则必须增加或减少其他数字以保持数字的连续顺序。

Here we change the priority of record two.

在这里,我们更改记录2的优先级。

If the priority is lowered (numeric value increased):

如果降低优先级(增加数值):

BeFORE CHANGE
CHANGE
AFTER CHANGE
1
1
2
4
4
3
2
4
3
5
5
更改之前
更改
变更后
1个
1个
2
4
4
3
2
4
3
5
5

If the priority is raised (numeric value decreased):

如果提高优先级(降低数值):

BeFORE CHANGE
CHANGE
AFTER CHANGE
1
1
2
3
3
4
4
2
2
5
5
更改之前
更改
变更后
1个
1个
2
3
3
4
4
2
2
5
5

优点 (Advantages)

  • The numbers will be persistent, no matter how the records are filtered or ordered无论记录如何过滤或排序,数字都将是永久性的
  • When maintained in a form, a new record will automatically be assigned the next higher number (lowest priority)当以表格形式维护时,新记录将自动分配给下一个较高的编号(最低优先级)
  • In the form, records can be inserted or deleted without breaking the sequentiality of the numbers在表格中,可以插入或删除记录,而不会破坏数字的顺序
  • Can easily, for example by a button-click, be reset to match the current sorting of the form可以轻松地重置(例如通过单击按钮)以匹配表单的当前排序
  • Will not degrade browsing in any way不会以任何方式降低浏览速度

缺点 (Disadvantages)

  • If records can be inserted or deleted from sources not maintaining the sequentiality of the numbers, this will be broken. However, sequentiality can be restored by a call to the function AlignPriority如果可以从不保持编号顺序的源中插入或删除记录,则记录将被破坏。 但是,可以通过调用AlignPriority函数来恢复顺序性

实作 (Implementation)

A form, a textbox, and a function that takes this textbox as an argument is required.

需要一个表单,一个文本框和一个以该文本框作为参数的函数。

A numeric and unique key is required, typical an AutoNumber named ID. If the name is not ID, it must be specified as the second parameter of the function.

需要数字和唯一键,通常是名为ID的自动编号。 如果名称不是ID,则必须将其指定为函数的第二个参数。

The function pulls all necessary information from the properties of this textbox, and then rearranges the full sequence of priority numbers to respect the change of value in this textbox by looping the RecordsetClone of the form.

该函数从此文本框的属性中提取所有必要的信息,然后通过循环表单的RecordsetClone来重新排列优先级数字的完整顺序,以尊重此文本框中的值更改。

Also here, the function is fully documented in-line, so you can read it line by line for the details:

同样在这里,该函数已全部内联文档,因此您可以逐行阅读以获取详细信息:

' Set the priority order of a record relative to the other records of a form.
'
' The table/query bound to the form must have an updatable numeric field for
' storing the priority of the record. Default value of this should be Null.
'
' Requires:
'   A numeric, primary key, typical an AutoNumber field.
'
' 2018-08-31. Gustav Brock, Cactus Data ApS, CPH.
'
Public Sub RowPriority( _
ByRef TextBox As Access.TextBox, _
Optional ByVal IdControlName As String = "Id")
' Error codes.
' This action is not supported in transactions.
Const NotSupported      As Long = 3246
Dim Form                As Access.Form
Dim Records             As DAO.Recordset
Dim RecordId            As Long
Dim NewPriority         As Long
Dim PriorityFix         As Long
Dim FieldName           As String
Dim IdFieldName         As String
Dim Prompt              As String
Dim Buttons             As VbMsgBoxStyle
Dim Title               As String
On Error GoTo Err_RowPriority
Set Form = TextBox.Parent
If Form.NewRecord Then
' Will happen if the last record of the form is deleted.
Exit Sub
Else
' Save record.
Form.Dirty = False
End If
' Priority control can have any Name.
FieldName = TextBox.ControlSource
' Id (primary key) control can have any name.
IdFieldName = Form.Controls(IdControlName).ControlSource
' Prepare form.
DoCmd.Hourglass True
Form.Repaint
Form.Painting = False
' Current Id and priority.
RecordId = Form.Controls(IdControlName).Value
PriorityFix = Nz(TextBox.Value, 0)
If PriorityFix <= 0 Then
PriorityFix = 1
TextBox.Value = PriorityFix
Form.Dirty = False
End If
' Disable a filter.
' If a filter is applied, only the filtered records
' will be reordered, and duplicates might be created.
Form.FilterOn = False
' Rebuild priority list.
Set Records = Form.RecordsetClone
Records.MoveFirst
While Not Records.EOF
If Records.Fields(IdFieldName).Value <> RecordId Then
NewPriority = NewPriority + 1
If NewPriority = PriorityFix Then
' Move this record to next lower priority.
NewPriority = NewPriority + 1
End If
If Nz(Records.Fields(FieldName).Value, 0) = NewPriority Then
' Priority hasn't changed for this record.
Else
' Assign new priority.
Records.Edit
Records.Fields(FieldName).Value = NewPriority
Records.Update
End If
End If
Records.MoveNext
Wend
' Reorder form and relocate record position.
' Will fail if more than one record is pasted in.
Form.Requery
Set Records = Form.RecordsetClone
Records.FindFirst "[" & IdFieldName & "] = " & RecordId & ""
Form.Bookmark = Records.Bookmark
PreExit_RowPriority:
' Enable a filter.
Form.FilterOn = True
' Present form.
Form.Painting = True
DoCmd.Hourglass False
Set Records = Nothing
Set Form = Nothing
Exit_RowPriority:
Exit Sub
Err_RowPriority:
Select Case Err.Number
Case NotSupported
' Will happen if more than one record is pasted in.
Resume PreExit_RowPriority
Case Else
' Unexpected error.
Prompt = "Error " & Err.Number & ": " & Err.Description
Buttons = vbCritical + vbOKOnly
Title = Form.Name
MsgBox Prompt, Buttons, Title
' Restore form.
Form.Painting = True
DoCmd.Hourglass False
Resume Exit_RowPriority
End Select
End Sub

It requires very little code in the form to work.

它只需要很少的代码即可工作。

If the textbox holding the priority field is named Priority, it will only be this:

如果包含优先级字段的文本框名为Priority ,则只能是以下形式:

After updating the Priority textbox:

更新优先级文本框后:

Private Sub Priority_AfterUpdate()
RowPriority Me.Priority
End Sub

After deleting or inserting a record, if that is allowed:

删除或插入记录后,如果允许的话:

Private Sub Form_AfterDelConfirm(Status As Integer)
RowPriority Me.Priority
End Sub
Private Sub Form_AfterInsert()
RowPriority Me.Priority
End Sub

That's it.

而已。

其他用法 (Other usage)

If the table with the priority field somehow can be scrambled by another process that is not aware of this field, or a table initially has no values filled in, a helper function is included, that will align the values to a given sort order.

如果具有优先级字段的表可以被不知道该字段的另一个进程扰乱,或者某个表最初没有填充值,则包含一个辅助函数,该函数将这些值与给定的排序顺序对齐。

It takes the recordset as the first parameter, and (re)arranges the priority field of this. If the field is not named Priority, pass its name as the second parameter.

它以记录集作为第一个参数,并(重新)排列其优先级字段。 如果该字段未命名为Priority ,则将其名称作为第二个参数传递。

The exact usage is described in the in-line comments in the header:

确切的用法在标题的内嵌注释中描述:

' Loop through a recordset and align the values of a priority field
' to be valid and sequential.
'
' Default name for the priority field is Priority.
' Another name can be specified in parameter FieldName.
'
' Typical usage:
'   1.  Run code or query that updates, deletes, or appends records to
'       a table holding a priority field.
'
'   2.  Open an updatable and sorted DAO recordset (Records) with the table:
'
'       Dim Records As DAO.Recordset
'       Set Records = CurrentDb("Select * From Table Order By SomeField")
'   3.  Call this function, passing it the recordset:
'
'       AlignPriority Records
'
' 2018-09-04. Gustav Brock, Cactus Data ApS, CPH.
'
Public Sub AlignPriority( _
ByRef Records As DAO.Recordset, _
Optional FieldName As String)
Const FirstNumber       As Long = 1
Const PriorityFieldName As String = "Priority"
Dim Field               As DAO.Field
Dim CurrentPriority     As Long
Dim NextPriority        As Long
If FieldName = "" Then
FieldName = PriorityFieldName
End If
' Verify that the field exists.
For Each Field In Records.Fields
If Field.Name = FieldName Then
Exit For
End If
Next
' If FieldName is not present, exit silently.
If Field Is Nothing Then Exit Sub
NextPriority = FirstNumber
' Set each record's priority to match its current position as
' defined by the sorting of the recordset.
Records.MoveFirst
While Not Records.EOF
CurrentPriority = Nz(Field.Value, 0)
If CurrentPriority = NextPriority Then
' No update needed.
Else
' Assign and save adjusted priority.
Records.Edit
Field.Value = NextPriority
Records.Update
End If
Records.MoveNext
NextPriority = NextPriority + 1
Wend
End Sub

Further, if the priority sequence needs a full rearrange, it can be done with, say, a button click - typically when the records of the form have been sorted in some way. For example:

此外,如果优先级序列需要完全重新排列,则可以通过单击按钮来完成-通常是在对表单的记录进行某种排序的情况下。 例如:

Private Sub ResetPriorityButton_Click()
SetRowPriority Me.Priority
End Sub

That will call this function which simply reads the property AbsolutPosition of every record:

这将调用此函数,该函数仅读取每个记录的属性AbsolutPosition

' Set the priority order of the records to match a form's current record order.
'
' The table/query bound to the form must have an updatable numeric field for
' storing the priority of the records. Default value of this should be Null.
'
' Usage:
'   To be called from, say, a button click on the form.
'   The textbox Me.Priority is bound to the Priority field of the table:
'
'       Private Sub ResetPriorityButton_Click()
'           SetRowPriority Me.Priority
'       End Sub
'
'
' 2018-08-27. Gustav Brock, Cactus Data ApS, CPH.
'
Public Sub SetRowPriority(ByRef TextBox As Access.TextBox)
Const FirstNumber       As Long = 1
Dim Form                As Access.Form
Dim Records             As DAO.Recordset
Dim FieldName           As String
Set Form = TextBox.Parent
Set Records = Form.RecordsetClone
' TextBox can have any Name.
FieldName = TextBox.ControlSource
' Pause form painting to speed up rebuilding of the records' priority.
Form.Painting = False
' Set each record's priority to match its current position in the form.
Records.MoveFirst
While Not Records.EOF
If Records.Fields(FieldName).Value = FirstNumber + Records.AbsolutePosition Then
' No update needed.
Else
' Assign and save adjusted priority.
Records.Edit
Records.Fields(FieldName).Value = FirstNumber + Records.AbsolutePosition
Records.Update
End If
Record   s.MoveNext
Wend
' Repaint form.
Form.Painting = True
Set Records = Nothing
Set Form = Nothing
End Sub

演示版 (Demo)

The form Products in the attached sample database - a subset of the Northwind 2007 Sample database - shows all three numbering methods side by side, and also the ID of the records:

随附的示例数据库中的Products表格是Northwind 2007示例数据库的子集,并排显示了所有三种编号方法以及记录的ID:

If you open it, you can try to sort and filter as you like and see, how the number sequences adopt.

如果将其打开,则可以尝试根据需要进行排序和过滤,并查看数字序列的采用方式。

Also, a button, Reset, is present to demonstrate a reset of the priority numbers.

此外,还有一个按钮Reset ,用于演示优先级数字的重置。

Further, a form, ProductsSlow, is included.

此外,还包括一个ProductsSlow形式。

This demonstrates the traditional code-less method to obtain row numbers using an expression with DLookup, one relative to field ID, and one relative to field Product Code. Also, for reference, a field, Record, displaying the record number is present.

这演示了使用带有DLookup的表达式来获得行号的传统的无代码方法,一个表达式相对于字段ID ,一个相对于字段Product Code 。 另外,作为参考,存在显示记录号的字段Record

The important thing here to notice is, that none of these fields are sortable in this form. In form Products, row number and priority are both sortable fields, as they are retrieved from the source query.

这里要注意的重要一点是,这些字段都不能以这种形式排序。 在表格Products中 ,行号和优先级都是可排序的字段,因为它们是从源查询中检索到的。

In module Demo, a function, PriorityCleanTest, is included to show how to call the function AlignPriority described above.

Demo模块中,包含一个函数PriorityCleanTest ,以显示如何调用上述函数AlignPriority

Also, two queries are included, showing typical usage of the functions.

此外,还包括两个查询,显示了该函数的典型用法。

Finally, as a practical example, a form is included where a custom Record of Records  control is included:

最后,作为一个实际示例,包括一个表格,其中有一个自定义的“ 记录记录”    控件包括:

(
)

结论 (Conclusion)

Three quite different methods for sequential numbering of records and rows have been described and listed, each with its advantages and disadvantages.

已经描述和列出了记录和行的顺序编号的三种完全不同的方法,每种方法都有其优点和缺点。

Combined with the first part on random enumeration, they are supposed to cover every real-life need.

结合有关随机枚举的第一部分,它们应该可以满足现实生活中的所有需求。

更多信息 (Further information )

The sequential numbering is part of a project on the general numbering of records.

顺序编号是项目中记录通用编号的一部分。

Random ordering is covered here: Random Rows in Microsoft Access

此处涵盖随机顺序: Microsoft Access中的随机行

Ranking rows is covered here: Ranking rows in Microsoft Access

此处包含排名行 : Microsoft Access中的排名行

A sample database in Access 365 is attached: RowNumbers 1.4.2.zip

附加了Access 365中的示例数据库: RowNumbers 1.4.2.zip

All current code can also be found on GitHub: VBA.RowNumbers

所有当前代码也可以在GitHub找到: VBA.RowNumbers

I hope you found this article useful. You are encouraged to ask questions, report any bugs or make any other comments about it below.

希望本文对您有所帮助。 鼓励您在下面提出问题,报告任何错误或对此作出任何其他评论。

Note: If you need further "Support" about this topic, please consider using the Ask a Question feature of Experts Exchange. I monitor questions asked and would be pleased to provide any additional support required in questions asked in this manner, along with other EE experts.

注意 :如果您需要有关此主题的更多“支持”,请考虑使用Experts Exchange 的“提问”功能。 我会监督提出的问题,并很高兴与其他电子工程师一起为以这种方式提出的问题提供所需的任何其他支持。

Please do not forget to press the "Thumbs Up" button if you think this article was helpful and valuable for EE members.

如果您认为本文对EE成员有用且有价值,请不要忘记按下“竖起大拇指”按钮。

翻译自: https://www.experts-exchange.com/articles/33069/Sequential-Rows-in-Microsoft-Access.html

access调整字段顺序

access调整字段顺序_Microsoft Access中的顺序行相关推荐

  1. access性别字段_12、ACCESS数据表的筛选(ACCESS图解操作系列)

    操作要求: 在ACCESS数据库"教学管理.accdb",其中有四个表:"教师"."学生"."课程"."选课成 ...

  2. Navicat:显示的行数与表中实际的行数不一致

    文章目录 1 Navicat 显示的行数 2 实际的行数 3 原因 1 Navicat 显示的行数 2 实际的行数 SELECTCOUNT(*) FROMtable1 3 原因 MySQL 在当前连接 ...

  3. access 重置索引_Microsoft Access中的索引

    access 重置索引 表中包含的数据越多,需要更多的索引来搜索和排序该数据. 但是,有足够的索引和太多的索引之间是一个平衡. 索引太多会减慢记录更新的速度. Access为您预设了许多索引. 如果您 ...

  4. access排名_在Microsoft Access中对行进行排名

    access排名 This is the third article on row numbers in Microsoft Access. 这是有关Microsoft Access中行号的第三篇文章 ...

  5. access调整行高和列宽,ACCESS2010复习知识点

    ACCESS复习知识点 第一部分数据库管理系统部分 第1章数据库系统概述 1.数据库系统的相关概念 2.数据库模型的种类及含义 3.关系模型及关系运算 第2章创建数据库 一.Access的基本知识 1 ...

  6. mysql access 2017_如何把Access的数据导入到Mysql中

    在建设网站的过程中,经常要处理一些数据的导入及导出.在Mysql数据库中,一般有两种方法来处理数据的导出: 1. 使用select * from table_name into outfile &qu ...

  7. 数据库工作笔记010---Mysql中用SQL增加、删除字段,修改字段名、字段类型、注释,调整字段顺序总结

    JAVA技术交流QQ群:170933152 Mysql中用SQL增加.删除字段,修改字段名.字段类型.注释,调整字段顺序总结 在网站重构中,通常会进行数据结构的修改,所以添加,删除,增加mysql表的 ...

  8. 如何把ACCESS的数据导入到Mysql中

    本源:网海拾贝 在设立设备网站的历程中,屡屡要处置一些数据的导入及导出.在Mysql数据库中,有两种方法来处置数据的导出(伟大). 1. 运用select * from table_name into ...

  9. powerdesigner 同步mysql 报错_PowerDesigner实用技巧小结 及 导出word,想字段顺序跟模型中一致,如何设置...

    powerdesigner导出word,想字段顺序跟模型中一致,如何设置 右键List of columns of the table %PARENT% ,selection,define  sort ...

最新文章

  1. CSS——float属性备忘笔记
  2. SuperSocket .net服务框架
  3. 计算机进制转换图,计算机等级考试进制转换及常用函数
  4. PBAS 背景建模源码浅析
  5. Network | 802.1x
  6. LINUX系统中动态链接库的创建与使用
  7. Sklearn参数详解—GBDT
  8. 4月8日--关于Date的练习题--自定义获取当前时间
  9. 牵手高通的百度是要拿科大讯飞开刀了?
  10. 腾讯首投AI芯片,领投燧原科技Pre-A轮3.4亿元融资
  11. C - Catch That Cow POJ - 3278(广搜)
  12. eclipse打开就闪退怎么办?
  13. 教你一招:Excel中使用vlookup函数查询序列所对应的值
  14. 动易自定义标签HTML输出,动易标签【ArticleList】
  15. python中merge函数_Python Merge函数原理及用法解析
  16. BlackBerry HTML5 WebWorks 平台下,让BB10应用连接上BBM
  17. 自然语言处理(七)——n元语法模型计算句子出现概率
  18. 【微信小程序】上传字体文件自定义字体family
  19. PPOJ1100: 诡异的楼梯
  20. 【论文】文本相似度计算方法综述

热门文章

  1. VBS 调用web接口
  2. 软件外包市场发展现状分析
  3. COSCon'19 女性参与开源论坛 ---女性,让开源社区更浪漫!
  4. 输出linux内核版本信息,查看linux内核和版本信息
  5. 10道不得不会的 Redis 面试题
  6. 计算机秋招国企总结,亲身经历风险
  7. python 爬虫 付费代理
  8. 著名基金经理彼得林奇的选股原则
  9. 如何不浪费时间-番茄工作法
  10. 【迷人的爪哇】—Java数据类型和变量