【问题标题】:Calculating time elapsed from current time in excel using VBA使用VBA在excel中计算从当前时间经过的时间
【发布时间】:2020-12-21 20:35:34
【问题描述】:

在我的程序中,用户填写了一个用户表单,该表单会自动生成在另一个 Excel 表上填写的信息和时间。我想使用 VBA 计算从表单的原始输入时间到当前时间的持续时间。我不明白为什么我的代码不起作用。当我尝试使用它时,持续时间一直为零。我不确定我需要从“Now()”中减去什么才能完成这项工作并给我一个实际值。

代码如下:

Private Sub cmdOkUpdate_Click()

Dim length As Date

length = Format(Now(), "hh:mm:ss")

strBOL = txtBOL.Value
strID = txtID.Value
details = txtDet.Value
opt = lbxOption.Value
currtime = time()
today = Format(Now(), "MM/DD/YYYY")
emp = TextBox1.Value
dur = Format(Now() - currtime, "hh:mm:ss")

If NoFill = True Then
    cellFill = ""
ElseIf NoFill = False Then
    With Sheet5

    .Range("A1").Value = "Time"
    .Range("B1").Value = "Date"
    .Range("C1").Value = "Location"
    .Range("D1").Value = "Category"
    .Range("E1").Value = "BOL"
    .Range("f1").Value = "Trailer #"
    .Range("g1").Value = "Details"
    .Range("H1").Value = "EE Name"
    .Range("I1").Value = "Duration"
    
    .Range("A2").EntireRow.Insert
    .Range("A2").Value = currtime
    .Range("B2").Value = today
    .Range("C2").Value = spot
    .Range("D2").Value = opt
    .Range("E2").Value = strBOL
    .Range("F2").Value = strID
    .Range("G2").Value = details
    .Range("H2").Value = emp
    .Range("I2").Value = dur
    
    .Columns("A:I").AutoFit
    
    End With

    If Not IsEmpty(opt) Then
        cellFill = opt & " " & vbCrLf & "BOL (last 5 digits): " & strBOL & " " & vbCrLf & "Trailer # " & strID & " " & vbCrLf & "Details: " & details & " " & vbCrLf & "EE Name: " & emp & " " & vbCrLf
        ActiveCell.Value = cellFill
        Call RealTimeTracker
    End If
    
End If


Unload Me
Sheet1.Activate


End Sub

【问题讨论】:

  • currtime = time() - 那是什么?
  • 你为什么使用Format()?此函数返回一个字符串。您想使用数值。 Now() 本来就是一个数值,不要转成字符串。
  • today = Format(Now(), "MM/DD/YYYY") 可以简化为 today = Date
  • 不管怎样,通过Timer()函数可以获取经过的时间。 Dim t As Single (或As Double 更精确),然后将当前计时器设置为 var t = Timer。然后当您需要经过的时间时:Debug.Print Timer - t Format() 在这方面可以,只是不能进行计算。在最后的评论中应该更清楚) 无论使用@ 987654333@ 或这个。这只是经过的秒数,可以根据需要进行转换。
  • 感谢您的帮助!我想从我的工作表上已经输入的时间中找到经过的时间。该时间来自 currtime = time () ,它自动生成用户填写表单的时间。所以我对从用户填写表格到现在所经过的时间感兴趣。

标签: excel vba time duration


【解决方案1】:

@Leah,您的代码实际上正在运行。如果你尝试这个(改编自你的代码),你会看到它工作:

Sub test()
    currtime = Time()
    waitTill = Now() + TimeValue("00:00:05")
    While Now() < waitTill
        DoEvents
    Wend
    dur = Format(Now() - currtime, "hh:mm:ss")
    MsgBox (dur)
End Sub

您遇到的问题是durcurrtime 太接近,因此,实际经过的时间为 0

您可以尝试将其放在代码中的较低位置,如下所示:

If NoFill = True Then
    cellFill = ""
ElseIf NoFill = False Then
    With Sheet5

    '...
    .Range("I2").Value = Format(Now() - currtime, "hh:mm:ss")
    '...
    End With

    '...
    
End If

但是,我认为这不会有什么不同,因为代码似乎没有做任何“复杂”到需要一秒钟以上的事情。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-10-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-09-29
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多