Excel 创建一个取决于当前年份的编号系统
我的电子表格用于管理任务。我通过运行一个小宏来添加新任务,当前编号仅为1、2、3、4…,由以下代码生成:Excel 创建一个取决于当前年份的编号系统,excel,vba,Excel,Vba,我的电子表格用于管理任务。我通过运行一个小宏来添加新任务,当前编号仅为1、2、3、4…,由以下代码生成: Cells(ActiveSheet.Rows(9).Row, 1).Value = Cells(ActiveSheet.Rows(10).Row, 1).Value + 1 我想使用VBA,通过在表示任务启动年份的数字上添加前缀来改进这一点。此外,每年第一次录入时,编号应从1开始。即 15-1, 15-2, 15-3, 15-4....16-1, 16-2, 16-3... 有什么简单
Cells(ActiveSheet.Rows(9).Row, 1).Value = Cells(ActiveSheet.Rows(10).Row, 1).Value + 1
我想使用VBA
,通过在表示任务启动年份的数字上添加前缀来改进这一点。此外,每年第一次录入时,编号应从1开始。即
15-1, 15-2, 15-3, 15-4....16-1, 16-2, 16-3...
有什么简单的代码可以实现这一点的想法吗?当然可以:
Cells(ActiveSheet.Rows(9).Row, 1).Value = format(date,"yy") & "-" & _
Cells(ActiveSheet.Rows(10).Row, 1).Value + 1
这个怎么样:
Sub Test()
Dim i As Integer
Dim startYear As Integer
priorYear = 2014
With ActiveSheet
For i = 1 To 100
.Cells(i, 1) = CStr(priorYear + WorksheetFunction.RoundUp(i / 12, 0) & "-" & ((i + 1) Mod 12))
Next i
End With
End Sub
这是一个非常基本的例子。修改它以适应你的需要。您还可以创建一个过程,并传递要自动编号的行号,如本文末尾所示
Sub Sample()
Dim rng As Range
Dim prev As Range
Dim rw As Long
rw = 9 '<~~ Change this to the relevant row
Set rng = ThisWorkbook.Sheets("Sheet1").Cells(rw, 1)
On Error Resume Next
Set prev = rng.Offset(-1)
On Error GoTo 0
'~~> Check if there is one row above
If Not prev Is Nothing Then
'~~> Match the year
If Left(rng.Offset(-1), 2) <> Format(Date, "yy") Then
'~~> Restart numbering
rng.Value = Format(Date, "yy") & "-" & 1
Else
'~~> Increment numbering. Split will extract the number
rng.Value = Format(Date, "yy") & "-" & Val(Split(rng.Value, "-")(1)) + 1
End If
Else
'~~> Restart numbering
rng.Value = Format(Date, "yy") & "-" & 1
End If
End Sub
子样本()
变暗rng As范围
变暗前照灯范围
变暗rw为长
rw=9'匹配年份
如果左(rng.Offset(-1),2)格式(日期,“yy”),则
“~~>重新开始编号
rng.Value=格式(日期,“yy”)&“-”和1
其他的
“~~>递增编号。Split将提取数字
rng.Value=格式(日期,“yy”)&“-”和Val(拆分(rng.Value“-”1))+1
如果结束
其他的
“~~>重新开始编号
rng.Value=格式(日期,“yy”)&“-”和1
如果结束
端接头
屏幕截图
编辑:
将其用作可以传递参数的过程
Sub Sample()
Dim r As Long
r = 9 '<~~ Chnage this to the relevant row
AllocateID r
End Sub
Sub AllocateID(rw As Long)
Dim rng As Range
Dim prev As Range
Set rng = Cells(rw, 1)
On Error Resume Next
Set prev = rng.Offset(-1)
On Error GoTo 0
'~~> Check if there is one row above
If Not prev Is Nothing Then
'~~> Match the year
If Left(rng.Offset(-1), 2) <> Format(Date, "yy") Then
'~~> Restart numbering
rng.Value = Format(Date, "yy") & "-" & 1
Else
'~~> Increment numbering. Split will extract the number
rng.Value = Format(Date, "yy") & "-" & Val(Split(rng.Value, "-")(1)) + 1
End If
Else
'~~> Restart numbering
rng.Value = Format(Date, "yy") & "-" & 1
End If
End Sub
子样本()
变暗,变长
r=9'匹配年份
如果左(rng.Offset(-1),2)格式(日期,“yy”),则
“~~>重新开始编号
rng.Value=格式(日期,“yy”)&“-”和1
其他的
“~~>递增编号。Split将提取数字
rng.Value=格式(日期,“yy”)&“-”和Val(拆分(rng.Value“-”1))+1
如果结束
其他的
“~~>重新开始编号
rng.Value=格式(日期,“yy”)&“-”和1
如果结束
端接头
每年第一次录入时,编号应从1开始。
;)谢谢大家!我用Siddharth Rout的代码把它整理好了:-)