【问题标题】:VBA code to serial number auto generation based on last cell value根据最后一个单元格值自动生成 VBA 代码到序列号
【发布时间】:2019-03-22 16:10:33
【问题描述】:

我在通过在 A 列中添加最后一个单元格值来自动生成序列号时遇到问题。我能够生成序列号直到 BA00935(通过添加最后一个单元格值 BA00934)但不是了解为什么代码没有生成序列号 BA00936 as in this figure。我什至没有收到任何错误消息。

我怎样才能以正确的方式使用row_number,或者有什么替代方法可以达到预期的效果?

我已使用以下 VBA 代码通过添加到最后一行来生成序列号。

Private Sub cmdadd_Click()
On Error Resume Next
ActiveSheet.Unprotect
Dim LastRow As Long
'for giving the serial number based on last cell value by adding plus one
With ActiveSheet
    LastRow = .Cells(.Rows.Count, "A").End(xlUp).Row
    Range("A" & LastRow).Select
    Selection.AutoFill Destination:=Range("A" & LastRow & ":A" & LastRow + 1), Type:=xlFillDefault
    Range("A" & LastRow + 1).Select
End With

Pattern_Serial nos

【问题讨论】:

  • BA00935在第 935 行吗?
  • 不,BA00935 在第 48 行
  • 那么模式是什么?
  • [描述](链接)
  • 我有一个用户表单,数据将从中填充到新行,所以我想要一个 vba 代码为每个新的生成自动序列号 'BA00935,BA00936,BA00937,.....'行,即在 A 列中添加上一个单元格值。

标签: excel vba userform


【解决方案1】:

假设字符串总是 7 个字符长并以 5 位数字结尾

Private Sub cmdadd_Click()
On Error Resume Next 'This line skips errors... bad practice unless you really know what you are doing
On Error GoTo 0
Dim LastRow As Long

With Workbooks(REF).Sheets(REF) 'Always refer to the wb/ws, otherwise VBA will refer to the active wb/ws

    .Unprotect

    'for giving the serial number based on last cell value by adding plus one
    LastRow = .Cells(.Rows.Count, "A").End(xlUp).Row
    prfx = Left(.Cells(LastRow, "A"),2) 'Gets the prefix by getting the 2 leftmost characters of the last filled cell
    nmbr = Right(.Cells(LastRow, "A"),5)+1 'Gets the last 5 characters, which is the number

    'Numbers don't have leading zeroes, so if the string did they have been stripped
    'This determines if that happened and if so, it adds as many leading zeroes as the number of characters is shorter than 5
    If Len(nmbr) < 5 Then 
        For i = 1 To (5 - Len(nmbr))
            nmbr = "0" & nmbr
        Next i
    End If
    .Cells(LastRow + 1, "A").Value = prfx & nmbr
End With
End Sub

【讨论】:

  • 感谢我刚刚尝试使用您的代码的代码,但它只能通过添加最后 5 位即 00936,00937... 我需要使用前缀 BA00936,BA00937..
  • 我编辑了我的代码,我给前缀变量起了一个坏名字。
  • 很高兴能帮上忙
猜你喜欢
  • 2016-08-16
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-04-12
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多