如何使用按钮将当前日期和时间添加到单元格?

How to add current date and time to a cell with a button?

我在 VBA Excel 中编写了代码,用于在特定单元格中从 0 开始增加值的按钮。

这个按钮的第二个特点应该是,当前日期和时间显示在从A2开始的A列中

如果“L13”中的值为 1,则当前日期和时间应出现在“A2”中,如果“L13”中的值为 2,则日期和时间应出现在 A3 中,以此类推,直至 A200。

我试着让它做不同的循环。

https://github.com/Cuyer/excel/blob/main/add_click

Sub Add_Click()
    Dim countCell As Range
    Set countCell = ActiveSheet.Range("L13")
    countCell = countCell + 1
   
    Dim wb As Workbook
   
    For Each wb In Application.Workbooks
        wb.Save
    Next wb
   
End Sub

VBA 中的 Date 函数将为您提供当天的日期值。

然后您可以将它分配给一个范围的值:

Activesheet.Range("A" & countCell + 1).Value = Date

我不确定您的意思是日期应该出现在单个单元格中,还是出现在与“L13”中的值相等的多个单元格中。上面的代码适用于单个单元格,但这里是你如何为多个单元格执行此操作:

ActiveSheet.Range("A2:A" & countCell + 1).Value = Date

Sub Add_Click()
   Dim countCell As Range, ws As Worksheet

   Set ws = ActiveSheet
   Set countCell = ws.Range("L13")
   countCell.Value = countCell.Value + 1
   'use Offset() to find the date cell
   ws.Range("A1").Offset(countCell.Value,0) = Date

   Dim wb As Workbook
   
   For Each wb In Application.Workbooks
       wb.Save
   Next wb
   
End Sub