我有一个userform,用户可以在其中插入数据,数据将在B列中插入到M.我需要一个代码,在工作表或用户窗体中自动填写序列号,以" RD 00001"每次输入数据时都会填写A列。请有人给我一个想法。
答案 0 :(得分:0)
这背后的代码非常简单,专为您开始,在Row 1
作为标题行的空白工作表上。它是动态的,所以基本上即插即用。只需使用您输入其他数据的任何代码调用sub。
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
注意:无论您要查找最后一行输入其他数据,请确保您的最后一行和此子行的最后一行相同。