[英]Excel Macro to Auto Generate ID using current Month, Year and number
單擊添加按鈕后,我試圖創建自動生成的字符串。 字符串由當前的Year,Month和序列組成。 yymm ## = 140501,其中##代表該月的數字。 如果我在同一個月再次單擊“添加”,則單擊140502。因此,最后2個數字遞增,其后是140503、140504、140505 ...
對於下個月,當我單擊“添加”時,它應該帶有140601、140602。對於新月,最后2個數字將重置為1。我嘗試了一下:
Sub AutoID()
Dim autoid1 As String
Dim intLastRow As Long
For i = 1 To 100
autoid1 = "FT" & Format(Date, "yymm") & i
Next
End Sub
這將創建您要的數字,但是一旦取消了靜態變量的范圍,它將失去記住該月的最后一個數字或是否是新月的能力。
Sub Test()
Dim i As Long
For i = 1 To 10
Debug.Print NewID
Next i
End Sub
Public Function NewID() As String
Dim m As String, y As String
Static inclNum As Integer
Static lastMonth As Integer
inclNum = inclNum + 1
m = Format(Date, "mm")
y = Format(Date, "yy")
If lastMonth = 0 Then lastMonth = CInt(m)
If CInt(m) <> lastMonth Then
lastMonth = CInt(m)
inclNum = 1
End If
NewID = CStr(inclNum)
If Len(NewID) < 2 Then NewID = "0" & NewID
NewID = y & m & NewID
End Function
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.