Excel VBA : Auto Generating Unique Number for each row

邮差的信 提交于 2019-12-01 14:47:29

You tagged with VBA, but you are not using VBA. Formulas that count rows or use the current row number will always update when the sheet re-calculcates.

In order to achieve what you describe, you really need VBA. A simple worksheet change event should do it. Think along the lines of

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

Copy the code, right-click the sheet tab, select "view code" and paste into the code window.

Here's a screenshot of before and after deleting row with ID 1002:

Sayyed Abbas Rizvi
Sub abc()
Dim a As Integer
Dim b As Integer
Dim i As Integer
Dim z As Integer

i = 1
Set sh = ThisWorkbook.Sheets("Sheet1") 'instead of sheet1 you can add name of your sheet
Dim k As Long
k = 2
Set rn = sh.UsedRange
k = rn.Rows.Count

Cells(1, 1).Value = 1001


Do Until i = k

b = (Cells(i, 1).Value)
a = b + 1
i = i + 1

Cells(i, 1).Value = a

Loop
End Sub

Not sure if you need a macro. You can add this macro to your file. Even after you delete the cell, once you run again the macro, the current cell value will be the value of the above cell plus one, so everthing will be according to series. Thanks

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