Search code examples
excelvbauserform

VBA code to serial number auto generation based on last cell value


I am Facing issue in auto generation of serial number by adding the last cell value in Column A. I was able to generate Serial number until BA00935(by adding the last cell values BA00934) but not understanding why the Code is not generating Serial number BA00936 as in this figure. I am not even getting any error message.

How can i use row_number in proper manner or is there any alternative to achieve the expected results?

I have used the following VBA Code to generate Serial number by adding to the lastrow.

Private Sub cmdadd_Click()
On Error Resume Next
ActiveSheet.Unprotect
Dim LastRow As Long
'for giving the serial number based on last cell value by adding plus one
With ActiveSheet
    LastRow = .Cells(.Rows.Count, "A").End(xlUp).Row
    Range("A" & LastRow).Select
    Selection.AutoFill Destination:=Range("A" & LastRow & ":A" & LastRow + 1), Type:=xlFillDefault
    Range("A" & LastRow + 1).Select
End With

Pattern_Serial nos


Solution

  • Assuming the strings are always 7 characters long and end in 5 digit numbers

    Private Sub cmdadd_Click()
    On Error Resume Next 'This line skips errors... bad practice unless you really know what you are doing
    On Error GoTo 0
    Dim LastRow As Long
    
    With Workbooks(REF).Sheets(REF) 'Always refer to the wb/ws, otherwise VBA will refer to the active wb/ws
    
        .Unprotect
    
        'for giving the serial number based on last cell value by adding plus one
        LastRow = .Cells(.Rows.Count, "A").End(xlUp).Row
        prfx = Left(.Cells(LastRow, "A"),2) 'Gets the prefix by getting the 2 leftmost characters of the last filled cell
        nmbr = Right(.Cells(LastRow, "A"),5)+1 'Gets the last 5 characters, which is the number
    
        'Numbers don't have leading zeroes, so if the string did they have been stripped
        'This determines if that happened and if so, it adds as many leading zeroes as the number of characters is shorter than 5
        If Len(nmbr) < 5 Then 
            For i = 1 To (5 - Len(nmbr))
                nmbr = "0" & nmbr
            Next i
        End If
        .Cells(LastRow + 1, "A").Value = prfx & nmbr
    End With
    End Sub