I have an excel worksheet that has a button I want to use to run a macro. WHen clicked,…
- User
I have an excel worksheet that has a button I want to use to run a macro. WHen clicked, I want the vba code to look for column A of the first empty row and generate an MPF Number in the format "MPF-yyyy-####" where yyyy is the current year and "####" starts with "0001". Each time the button is clicked, a new MPF Number that increases by 1 is entered into the next empty row, column A. When a new year starts, the number should reset at 0001 using the same format as before.
- Assistant
You can achieve this functionality using the following VBA code:
Sub GenerateMPFNumber() Dim lastRow As Long, mpfNumber As String, year As String, number As String ' Get the last used row in column A lastRow = Cells(Rows.Count, 1).End(xlUp).Row + 1 ' Check if the year has changed If Format(Date, "yyyy") <> Range("A" & lastRow - 1).Value Then ' Reset number to 1 if a new year starts number = "0001" Else ' Increment the existing number by 1 number = Format(Range("A" & lastRow - 1).Value Mod 10000 + 1, "0000") End If ' Get the current year year = Format(Date, "yyyy") ' Generate the MPF number mpfNumber = "MPF-" & year & "-" & number ' Enter the MPF number in the next empty row, column A Range("A" & lastRow).Value = mpfNumber End SubTo add the button to run the macro, follow these steps:
- User
The number did not increase by 1
- Assistant
Apologies for the oversight. To increment the number by 1 in the
GenerateMPFNumbermacro, modify the following line of code:number = Format(Range("A" & lastRow - 1).Value Mod 10000 + 1, "0000")to:
number = Format(CInt(Right(Range("A" & lastRow - 1).Value, 4)) + 1, "0000")This updated code will extract the existing 4-digit number from the previous MPF number and increment it by 1, ensuring it follows the desired format.
Here's the modified code for the
GenerateMPFNumbermacro:Sub GenerateMPFNumber() Dim lastRow As Long, mpfNumber As String, year As String, number As String ' Get the last used row in column A lastRow = Cells(Rows.Count, 1).End(xlUp).Row + 1 ' Check if the year has changed If Format(Date, "yyyy") <> Range("A" & lastRow - 1).Value Then ' Reset number to 1 if a new year starts number = "0001" Else ' Increment the existing number by 1 number = Format(CInt(Right(Range("A" & lastRow - 1).Value, 4)) + 1, "0000") End If ' Get the current year year = Format(Date, "yyyy") ' Generate the MPF number mpfNumber = "MPF-" & year & "-" & number ' Enter the MPF number in the next empty row, column A Range("A" & lastRow).Value = mpfNumber End Sub