函数1:
Function MinutesBetweenTimes(startTime As Date, endTime As Date) As Long
' 计算两个时间的分钟差
MinutesBetweenTimes = DateDiff("n", startTime, endTime)
End Function
或者(加了个参数,分别计算秒、分、时、天、年):
Function MinutesBetweenTimes(startTime As Date, endTime As Date, i As Integer) As Long
Dim tt As String
If i = 0 Or i = False Then
tt = "s"
ElseIf i = 1 Then
tt = "n"
ElseIf i = 2 Then
tt = "h"
ElseIf i = 3 Then
tt = "d"
Else
tt = "yyyy"
End If
MinutesBetweenTimes = DateDiff(tt, startTime, endTime)
End Function
输出:
Sub CalculateMinuteDifference()
Dim startTime As Date
Dim endTime As Date
Dim minutesDifference As Long
' 示例时间
startTime = CDate("2023-04-01 08:00:00")
endTime = CDate("2023-04-01 09:30:00")
' 调用函数计算时间差
minutesDifference = MinutesBetweenTimes(startTime, endTime)
' 输出结果
Debug.Print "分钟数差异: " & minutesDifference
End Sub
函数2【测试结果不管用】:
Function TimeDifference(time1 As Range, time2 As Range) As Variant
Dim diff As Variant
Dim hours As Integer, minutes As Integer
hours = Hour(time2.Value - time1.Value)
minutes = Minute(time2.Value - time1.Value)
TimeDifference = hours & "小时" & Format(minutes, "00") & "分"
End Function