![](/img/trans.png)
[英]How to Calculate time difference in difference format in Excel using VBA
[英]How to calculate the time difference using VBA?
我是 VBA 的初学者。 我只需要在 VBA 中解决我的问题。 谢谢。
以下是我需要完成的任务
从表中选择一个“ID”和一个“课程”。 在下表中,我提到了几个 ID 和课程,但是我的项目有多个 ID 和课程。 我不能在所有情况下都输入 ID 和课程名称。 有没有聪明的方法来做到这一点?
对于特定的 ID、特定的课程和特定的日期,我需要计算下表中针对特定“事件”给出的两行之间的时间差。 前两行的时间差给出了“阅读”所花费的时间,第 2 行和第 3 行之间的时间差给出了“写作”所花费的时间,第 3 行和第 4 行之间的差异给出了“写作”所花费的时间,依此类推.
任何帮助将不胜感激。 数据格式在下面的链接中
您可以修改代码并尝试:
Option Explicit
Sub test()
Dim strID As String, strCourse As String, strEvent As String
Dim DateTime1 As Date, DateTime2 As Date
Dim LastRow As Long, i As Long, y As Long
With ThisWorkbook.Worksheets("Sheet1")
LastRow = .Cells(.Rows.Count, "A").End(xlUp).Row
For i = 2 To LastRow
strID = .Range("A" & i).Value
strCourse = .Range("B" & i).Value
DateTime1 = CDate(.Range("C" & i).Value) & " " & CDate(.Range("D" & i).Value)
strEvent = .Range("E" & i).Value
For y = 2 To LastRow
If y <> i Then
If .Range("A" & y).Value = strID And .Range("B" & y).Value = strCourse And .Range("E" & y).Value = strEvent And .Range("F" & i).Value = "" And .Range("F" & y).Value = "" Then
DateTime2 = CDate(.Range("C" & y).Value) & " " & CDate(.Range("D" & y).Value)
.Range("F" & i).Value = Abs(DateDiff("h", DateTime2, DateTime1))
End If
End If
Next y
Next i
End With
End Sub
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.