问题
I have a userform in which user can insert data and data will insert in column B to M. I need a code, either in worksheet or in userform to auto fill serial number starting with "RD 00001" which will fill in column A everytime data has enter. Please someone give me an idea.
回答1:
The code behind this is very simple and designed for you to start on a blank sheet with Row 1
being your header row. It's dynamic so essentially plug and play. Just call on the sub with whatever code you have for entering in the other data.
Sub SerialCode()
Dim ws As Worksheet
Dim lastSerial, digits, i As Integer
Dim nextRow, lastRow As Long
Dim newSerial As String
Set ws = ThisWorkbook.Sheets(1)
nextRow = ws.Cells(ws.Rows.Count, "A").End(xlUp).Row + 1 'Finds the last row in A
lastRow = nextRow - 1
newSerial = "" 'set value of our string blank
If (nextRow - 1) < 2 Then 'If statement to catch if there's only a header
lastSerial = 0
Else: lastSerial = CInt(Replace(ws.Range("A" & lastRow).Value, "RD ", ""))
End If
lastSerial = lastSerial + 1
digits = 6 - Len(lastSerial) 'how many 0's are there
For i = 1 To digits
newSerial = newSerial & "0" 'start building the string with 0's
Next i
newSerial = "RD " & newSerial & lastSerial 'concatenate the serial code
ws.Range("A" & nextRow).Value = newSerial
End Sub
NOTE: whatever you have for finding your last row to input the other data, make sure your last row and this sub's last row are the same.
来源:https://stackoverflow.com/questions/39360611/vba-code-to-auto-serial-number-in-column-a-after-my-userform-entered-data-in-col