Wednesday, March 25, 2015

Automate serial number using Formula, Macro and Worksheet Change event

Have you ever know you can automate the serial numbering in excel. You can achieve this in multiple way using formulas and macros. 
You want to automate the serial numbering in live when entering data just set the formulas in appropriate column in worksheet. Also you can use Worksheet_Change event to automate the serial numbering to your data. 
You have the data set already then have to use either formula or macro. Using macro you can achieve this by one click away otherwise have to do some copy and paste or fill handle options.

So many formulas are available in internet, here is the best one I ever used.
Assume having column headers in row 1,

=IF(ISBLANK(B2),"",COUNTA($B$2:B2))

Paste the above formula in cell A2 and copy down or where you need to have the serial number. When the column B is filled, the serial number will be automatically generated in column A.


When you insert a row, you need to copy the formula from the row above to the new row and the row below it. This is more irritating thing for me.

Automate serial numbering using VBA macro is given below.

Private Sub Worksheet_Change(ByVal Target As Range)
Dim MaxNo
If Not Intersect(Target, Range("B:B")) Is Nothing Then
    'More than one row is changed do not run
    If Target.Rows.Count > 1 Then Exit Sub
    'Do not run if column A in the current row has a value
    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 in column A
    MaxNo = Application.WorksheetFunction.Max(Range("A:A"))
    Target.Offset(0, -1) = MaxNo + 1
End If
End Sub