在VBA中格式化为字符串时的时间比较?

时间:2018-06-08 09:23:34

标签: excel vba excel-vba

我有两个列,让我们说"A""B",它们存储时间值并格式化为字符串。

例如,"A"'09:40'"B"个商店'10:00'存储在第一行。

我需要比较时间值并检查"B"是否大于"A"

我发现了类似的问题here,但它假设单元格格式为日期。

我也试过这个:

   'colB' and 'colA' store the column letter, 'i' is an iterator over the rows
If Range(colB & i).Value2 = Range(colA & i).Value2 Then 
   'some code
End If 

但它显然不适合这种情况,因为它无法比较时间值。

我该怎么做?

3 个答案:

答案 0 :(得分:0)

我通常会将这些值放在日期格式中,让Excel关注它。不过,您可以尝试使用自定义函数自行进行比较:

Option Explicit

Sub TestMe()

    Dim firstVal As String: firstVal = "09:40"
    Dim secondVal As String: secondVal = "10:00"

    Debug.Print isFirstValBigger(firstVal, secondVal)
    Debug.Print isFirstValBigger(firstVal, secondVal, True)

End Sub

Public Function isFirstValBigger(firstVal As String, secondVal As String, _
                                Optional isSecondValBigger As Boolean = False) As Boolean

    Dim firstTime As Date
    Dim secondTime As Date

    firstTime = TimeSerial(Split(firstVal, ":")(0), Split(firstVal, ":")(1), 0)
    secondTime = TimeSerial(Split(secondVal, ":")(0), Split(secondVal, ":")(1), 0)

    If isSecondValBigger Then
        isFirstValBigger = CBool(secondTime > firstTime)
    Else
        isFirstValBigger = CBool(firstTime > secondTime)
    End If

End Function

isFirstValBigger返回布尔结果,第一个值是否更大。如果你想改变第二个值,那么有一个可选变量 - isSecondValueBigger

答案 1 :(得分:0)

Sub FormatTime()

    Dim Time1 As Date
    Dim Time2 As Date

    Time1 = Left(Range(colB & i).Value, 2) & ":" & Right(Range(colB & i).Value, 2)
    Time2 = Left(Range(colA & i).Value, 2) & ":" & Right(Range(colA & i).Value, 2)
    Format Time1, Format:="hh:mm"
    Format Time2, Format:="hh:mm"

    If Time1 < Time2 Then
    'Do what you want to do
    End If

End Sub

答案 2 :(得分:0)

没有必要使用VBA。 Excel可以轻松转换值:

=TIMEVALUE(B1)>TIMEVALUE(A1)

或者,使用双一元来强制转换:

=--B1>--A1

或对值使用任何其他数学运算:

=(B1-A1)>0

使用数学运算方法的优点在于它对值是字符串还是数字不敏感

而且,在VBA中,转换也很容易被强制(并且对数据类型也不敏感)

Function timeDiff(A, B) As Boolean
    timeDiff = CDate(A) > CDate(B)
End Function

使用公式:

=timeDiff(B1,A1)