【发布时间】: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更精确),然后将当前计时器设置为 vart = Timer。然后当您需要经过的时间时:Debug.Print Timer - t(Format()在这方面可以,只是不能进行计算。在最后的评论中应该更清楚) 无论使用@ 987654333@ 或这个。这只是经过的秒数,可以根据需要进行转换。 -
感谢您的帮助!我想从我的工作表上已经输入的时间中找到经过的时间。该时间来自 currtime = time () ,它自动生成用户填写表单的时间。所以我对从用户填写表格到现在所经过的时间感兴趣。