Excel VBA:自动编号

我正在Excel上创build一个数据库,并遇到一些问题,因为我试图给每行分配自动编号。

要求是:

  1. 当列B不为空时,为每一行(列A)生成自动编号。
  2. 该数字应该是唯一的,并且即使在列被sorting或插入新行时也必须始终连接到同一行的内容。
  3. 当插入一个新的行时(同一列的任何地方),应该分配一个新的数字(最新的数字应该是最大的数字)if
  4. 可能的话,自动号码应该有一个前缀,号码应该显示在四个数字(例如0001,0011)

我已经尝试了一些VBA代码,我发现从其他人的问题(例如Excel VBA:自动生成每行的唯一编号 )。

到目前为止,下面的代码运行得最好,但是这个代码不能解决(3)和(4)的要求。

Private Sub Worksheet_Change(ByVal Target As Range) Dim maxNumber If Not Intersect(Target, Range("B:B")) Is Nothing Then ' don't run when more than one row is changed If Target.Rows.Count > 1 Then Exit Sub ' if column A in the current row has a value, don't run If Cells(Target.Row, 1) > 0 Then Exit Sub ' get the highest number in column A, then add 1 and write to the ' current row, column A maxNumber = Application.WorksheetFunction.Max(Range("A:A")) Target.Offset(0, -1) = maxNumber + 1 End If End Sub 

我缺乏VBA的知识,我希望有人能帮助我。 非常感谢。

不要使用Max()来查找下一个数字 – 而是使用隐藏的表格或名称来存储当前的数字,并在每次需要新的Id时递增。

例如:

 Public Function NextNumber(SequenceName As String) Dim n As Name, v On Error Resume Next Set n = ThisWorkbook.Names(SequenceName) On Error GoTo 0 If n Is Nothing Then 'create the name if it doesn't exist ThisWorkbook.Names.Add SequenceName, RefersTo:=2 v = 1 Else 'increment the current value v = Replace(n.RefersTo, "=", "") n.RefersTo = v + 1 End If NextNumber = v End Function 

这允许你使用多个不同的序列,只要你给每一个不同的名字。

 Dim seq seq = NextNumber("seqOne") 'etc