首页 > 解决方案 > VBA-每次单击同一行中的按钮时添加时间戳

问题描述

我是 VBA 新手,需要一些帮助。到目前为止,我已经能够创建一个用户表单来保存每次单击按钮时的时间戳。这是工作表上的格式:

时间 用户 样本 属性
“hh:mm:ss” 姓名 000 甜的

该表还存储单击“属性”列下的“开始”按钮时的情况。按钮可能会被点击,也可能不会被点击,它们可能会被多次点击。我想使用“开始”的时间戳作为参考来计算按钮点击的时间差,控制每个用户和样本组合。我知道有一个 DateDiff 函数,但不确定在这种情况下如何使用它。这就是我想要的: 数据设置

这是开始按钮的代码:

    Private Sub CmmdBtnStart_Click()
    'Close form after 30 seconds from clicking Start
    countdown = Now + TimeValue("00:00:30")
    Application.OnTime countdown, "UnloadIt"
   
    'Add timestamp of Start Button
    Dim wsData As Worksheet
    Dim BtnStart As String
    Dim lastrow As Long
    Set wsData = Worksheets("Data")

    With wsData
    lastrow = wsData.Cells(.Rows.Count, 1).End(xlUp).Offset(1, 0).Row
    BtnStart = CmmdBtnStart.Caption
    End With

    With wsData
    'Add time it was clicked
        With .Cells(lastrow, 1)
             .Value = Now
             .NumberFormat = "hh:mm:ss"
        End With
        'Add user name
        .Cells(lastrow, 2).Value = txtboxuser.Value
        'Add sample code
        .Cells(lastrow, 3).Value = txtboxsample.Value
        'Get button caption or text and add to worksheet
        .Cells(lastrow, 4).Value = BtnStart
    End With

    End Sub

每个按钮都有一个类似的代码来向工作表添加数据。我需要用户表单中的代码,还是可以在工作表中完成?我会很感激任何帮助。

标签: excelvba

解决方案


推荐阅读