Excel VBA Course
Excel VBA Course - From Beginner to Expert

200+ Video Lessons
50+ Hours of Video
200+ Excel Guides

Become a master of VBA and Macros in Excel and learn how to automate all of your tasks in Excel with this online course. (No VBA experience required.)

View Course

Unique Sequential Numbers

0

I have a tracker for my cases and I would like to know how to create a macro that will begin a sequential number starting with 21-001 to track cases and adding 1 every time someone presses a button. For example if I'm starting my second case, I press my "New Case" button and it automatically creates the next sequential number 21-002. Also if possible I would like for the number convention to start all over at the beginning of the next year. For example, in 2022 I would like it to start at 22-001. 

Answer
Discuss

Answers

1

You are too modest, Papo. When you deal with Excel you should allow your imagination to roam more freely. For example, why ask to insert a number while in reality you want a row with the number already in it? Or, why do you need a button while looking at a worksheet consisting, literally, of a billion buttons?

The code I offer you below allows you to double-click on the cell immediately below the last available number, in fact, the blank cell where you want the new number to appear. It will insert a row coping all cell formats and formulas from the row above and insert the new number (changing count with the year as you describe).

Private Sub Worksheet_BeforeDoubleClick(ByVal Target As Range, Cancel As Boolean)
    ' 166
 
    Const NumberClm     As Long = 1             ' change to suit (1 = column "A")
    Dim Trigger         As Range
    Dim Rnew            As Long                 ' new row number
    Dim Number          As Long
    
    Set Trigger = Cells(Rows.Count, NumberClm).End(xlUp).Offset(1)
    With Target
        If .Address = Trigger.Address Then
            Number = .Offset(-1).Value
            Rnew = AppendRow(.Row)
            Cancel = True
            
            With Cells(Rnew, NumberClm)
                .Value = NextNumber(Number)
                .NumberFormat = "00-000"
                .Offset(0, 1).Select                ' select the next cell
            End With
        End If
    End With
End Sub
 
Private Function AppendRow(ByVal Rt As Long, _
                           Optional ByVal Rs As Long) As Long
    ' 166
    ' return the number of the inserted row
    
    ' copy from previous row (can't create first data row) if Rs isn't specified
    If Rs = 0 Then Rs = Rt - 1
    With ActiveSheet
        .Rows(Rs).Copy
        .Rows(Rt).Insert Shift:=xlDown
        On Error Resume Next
        ' delete any existing values
        .Rows(Rt).SpecialCells(xlCellTypeConstants).ClearContents
        On Error GoTo 0
    End With
    
    AppendRow = Rt
    Application.CutCopyMode = False
End Function
 
Private Function NextNumber(ByVal Number As Long) As Long
    ' 166
 
    Dim Annual          As Integer
    Dim Serial          As Integer
 
    Annual = Int(Number / 1000)
    If Annual = (Year(Date) Mod 1000) Then
        Serial = Number Mod 1000
    Else
        Annual = (Year(Date) Mod 1000)
    End If
    NextNumber = Annual * 1000 + Serial + 1
End Function

Important! Install the code in the code module of the worksheet on which you want the action.

The code is structured in 3 easy to maintain parts. The first part replaces the button. It's an event procedure which fires when you doujble-click and ensures that action is taken only when one particular cell is clicked. You can help define the cell by changing the value of the constant NumberClm.

The event procedure then calls the other two functions. The first one inserts a new row and informs the caller of the number of that row. The second one calculates the new number from the old.

Finally, the event procedure does two more things.

  1. It formats the cell where the number appears. This is because there is a number in that cell, like 21001, not a  text string like "21-001". That makes it easier to work with the number because, well, because it's a real number. However, you want the number to appear like 21-001. Therefore you need to apply a cell format. Of course, as you copy rows down the format is also copied. Inserting it isn't therefore necessary, strictly speaking, but I added it just to be sure
  2. The procedure then selects the next cell because, of course, you will not start writing in the cell where the number was inserted but somewhere else. You can change the code to select the cell you want to start working at.
Discuss

Discussion

Nice! @ Variatus- I like it, offers some advantages and is more sophisticated than my crude (but shorter) effort.
John_Ru (rep: 6152) Feb 4, '21 at 4:15 am
@John_Ru Thank you for the applause. But the way to show appreciation is to upvote. Comments tend to be judgmental, like "more sophisticated but ...". 
Variatus (rep: 4889) Feb 4, '21 at 6:53 pm
@Variatus - done. I didn't mean to be judgemental. 
John_Ru (rep: 6152) Feb 5, '21 at 1:26 am
Add to Discussion
0

Papo

This will work if your tracking numbers are stored sequentially in column A of the sheet where your button is (like my file attached) AND the last entry is the last number allocated. Click the green button (currently in column A) and new numbers will be added.

It works by finding the last used row. The If test (in bold below) compares the last two digits of the current year (from Year(Now()), i.e. the year of todays date ), say 21, with the first two digits of the last used cell in A. If it's the first row (so no numbers yet), it makes n become 1.  Likewise if early next rear (or later years) it compares "21" from the last cell with 22 for the new year.

Otherwise, it adds 1 to n (the last 3 digits of the last tracking number).

Then it sets the next cell down to the two year digits, plus a "-" and the incremented number.

Private Sub CommandButton1_Click()

Dim r As Integer, n As Integer

r = Range("A" & Rows.Count).End(xlUp).Row 'find last used row

If Right(Year(Date), 2) <> Left(Range("A" & r), 2) Then 'if no tracking number yet or year changed
    n = 1
    Else 'normally take last 3 digits of last and add 1
    n = Right(Range("A" & r).Value, 3) + 1
End If
'set next cell to desired format
Range("A" & r + 1) = Right(Year(Now()), 2) & "-" & Format(n, "00#")

End Sub
You can't check that the year end bit works as it stands but you could do this check (to simulate a change of year) to see that the trailing number bit resets: 1) Click the button a few times so you have numbers in column A. 2) Change the If statement above to this (in the VB Explorer):
If Right(Year("01/01/2022"), 2) <> Left(Range("A" & r), 2) Then
(which will give the year of that bold 22 date) and if you click the button again, the numbers will restart from 001. 3) Undo that change in VB Explorer and delete the test values in A.

Hope this works for you.

Discuss

Discussion

Papo

In the file I sent, I  forgot to freeze the worksheet (top row and/or 1 or more columns), Suggest you do that so that the button is always visible, no matter how far down the file you are.

Also you might also want to have the new cell/number selected by adding this, just before End Sub:
Range("A" & r + 1).Select
John_Ru (rep: 6152) Feb 4, '21 at 4:11 am
John,

Thank you for the code and understanding. I got the macro to work on my excel but I'm using excel as database. I have three sheets. One sheet, is where I hold my data (which is very hidden from users) and the second sheet, is my main menu and the last sheet, is where I input the information so I can save my data and transfer the information to my "datasheet".  Now that I have the macro you showed me in place to my datasheet in my excel, is there any way I can transfer my new sequential number show up in my input sheet? Does that make sense? I wish there was a way I can upload my excel so you guys can see it. 
papo1108 Feb 4, '21 at 6:06 pm
Papo, you can upload your Excel file- edit your original Question and use the "Add file..." button below the text of the question. Please be sure to disable any passwords so we can work with file.

I'm sure the new number can be displayed in your input sheet. Have you tried adding this near the end of the macro (changing the bits in bold to suit)? 
 Worksheets("Input"). Range("B7") = Right(Year(Now()), 2) & "-" & Format(n, "00#")
John_Ru (rep: 6152) Feb 4, '21 at 6:23 pm
Papo. Did you succeed?
John_Ru (rep: 6152) Feb 8, '21 at 4:43 am
John,

I did the code and it worked but all of sudden I got a
"Run-Time error '1004':

Application-defined or object-defined error"

When the above error appears vba highlights the formatting code. Please help. 
papo1108 Feb 10, '21 at 12:36 pm
Papo

I think you mean that the error appears against the additional suggestion above:
Worksheets("Input"). Range("B7") = Right(Year(Now()), 2) & "-" & Format(n, "00#")

If so, I suspect that you changed the line to refer to a different cell, perhaps changed ...Range("B7").... to Range(G2) say but forgot to put the inverted commas around the cell reference G2 or whatever.

Don't forget that if my Answer addressed your Question you should mark it Selected (or choose the one from @Variatus if that's better for you). It seems to me that my Answer did so (but you're asking about the extra suggestion I made to help you further)..
John_Ru (rep: 6152) Feb 10, '21 at 1:03 pm
Add to Discussion


Answer the Question

You must create an account to use the forum. Create an Account or Login