使用VBA为事务生成自动引用

时间:2015-12-15 16:24:50

标签: excel vba excel-vba

我正在尝试编写代码来生成自动事务引用以及将其分配给员工,任何人都可以帮助我找到使其增量的等式,例如引用为COMP100015/12/2015,下一个将是COMP100115/12/2015

我使用的代码:

Sub LeftArrow2_Click()
 Dim RowCount As Long

 Dim cell As Range, Rng As Range

RowCount = Worksheets("Sheet1").Range("A1").CurrentRegion.Rows.Count
  With Worksheets("Sheet1").Range("A1")

  .Offset(RowCount, 1).Value = Environ("username")
  .Offset(RowCount, 0).Value = "COMP" & Date
  .Offset(RowCount, 2).Value = Format(Now, "dd/mm/yyyy hh:nn:ss")

End With

End Sub

此代码的结果:

reference   Officer                Date 
COMP15/12/2015  aselhayani  15/12/2015 18:10:18
COMP15/12/2015  aselhayani  15/12/2015 18:10:19

2 个答案:

答案 0 :(得分:0)

我会像这样调整代码:

Sub LeftArrow2_Click()

Dim RowCount As Long
Dim cell As Range, Rng As Range, i As Long

RowCount = Worksheets("Sheet1").Range("A1").CurrentRegion.Rows.Count
With Worksheets("Sheet1").Range("A1")

    .Offset(RowCount, 1).Value = Environ("username")
    ' Get the next index based on the prior index, if it existed, adding one to it.
    On Error Resume Next: i = Val(Mid(.Offset(RowCount - 1, 0).Value, 5, 4)) + 1: On Error GoTo 0
    ' Put the index in, formatted to 4 zeroes.
    .Offset(RowCount, 0).Value = "COMP" & Format(i, "0000") & Date
    .Offset(RowCount, 2).Value = Format(Now, "dd/mm/yyyy hh:nn:ss")

End With

End Sub

答案 1 :(得分:0)

假设您需要在第1列中进行交易参考,请尝试以下方法:

Sub LeftArrow2_Click()
 Dim RowCount As Long

 Dim cell As Range, Rng As Range

 RowCount = Worksheets("Sheet1").Range("A1").CurrentRegion.Rows.Count

 With Worksheets("Sheet1").Range("A1")
     .Offset(RowCount, 1).Value = Environ("username")
     .Offset(RowCount, 0).Value = "COMP" & CInt(Mid(.Offset(RowCount-1, 0).Value, 5, 4)) + 1 & Date
     .Offset(RowCount, 2).Value = Format(Now, "dd/mm/yyyy hh:nn:ss")
 End With

End Sub