0

每次执行 Makro 时,我都试图在 Sheet1 的 A1 中生成一个数字。该数字是日期和要递增的数字的组合。最终编号将传输到 A 列中尚无数据的 Sheet2(在本例中为 A1>A2>A3>....)

这是我对工作表函数的尝试,并用作可视化

这是我在 VBA 中的尝试,但它什么也没做。

Sub incrementInvoiceNumber()
  Dim rng_dest As Range
  Dim i As Long

  Application.ScreenUpdating = False
  Sheets("Sheet1").Range("A1").Value = WorksheetFunction.Text(Date, "YYYYMMDD") & WorksheetFunction.Text(Range("A1").Value + 1)
  i = 1
  Set rng_dest = Sheets("Sheet2").Range("A:A")
  Do Until WorksheetFunction.CountA(rng_dest.Rows(i)) = 0
   i = i + 1
  Loop

 Sheets("Sheet2").Range("A" & i).Value = Sheets("Sheet1").Range("A1").Value

 Application.ScreenUpdating = True
End Sub
4

1 回答 1

0

目前还不清楚究竟是什么导致代码不起作用。我认为它的父表没有调用一些愤怒。

此外,如果你有可以做同样事情的 VBA 函数,最好避免 WorksheetFunction。

并且,可以通过使用方法以更好的方式找到最后一行End()

这是如何:

Sub incrementInvoiceNumber()
    Dim i As Long
    Application.ScreenUpdating = False

    Sheets("Sheet1").Range("A1").Value = _
        Format(Date, "YYYYMMDD") & Format(Sheets("Sheet1").Range("A1").Value + 1) 'Make sure Sheet1 is the sheet with the value. Fix it if otherwise

    With Sheets("Sheet2")
        i = .Cells(.Rows.Count, 1).End(xlUp).Row
        If Not IsEmpty(.Cells(i, 1)) Then i = i + 1
        .Cells(i, 1).Value = Sheets("Sheet1").Range("A1").Value
    End With

    Application.ScreenUpdating = True
End Sub

Cells(Rows.Count, 1).End(xlUp)表示如果从 A 列中的最后一个单元格(“A1048576”)开始并按 Ctrl + 向上箭头,您将到达的单元格。

于 2020-04-06T18:35:51.423 回答