首页 文章

Excel VBA等于时间不匹配

提问于
浏览
1

我在Excel中有这个VBA代码:

If (TimeValue(C_CurrentDate) = L_CurrentStartTime) Then
   do-someting
End If

但它永远不会做“某事” .

示例数据是C_CurrentDate - > 17/03/2014 2:05:00和L_CurrentStartTime - > 2:05:00

比较的两边应该是2:05:00,但它仍然不匹配 . 我甚至将它们都转换为msgbox中的两倍,它们都呈现8,68055555555556E-02

它们作为Doble值的差异在E-17范围内 .

怎么会这样?两个值都已从单元格数据中读取 .

2 回答

  • 0

    只需丢弃组合DateTime的日期部分:

    Sub TestOfTime()
        Dim C_CurrentDate As String, L_CurrentStartTime As String
        Dim d1 As Date, d2 As Date
    
        C_CurrentDate = "17/03/2014 2:05:00"
        L_CurrentStartTime = "2:05:00"
    
        d1 = TimeValue(Split(C_CurrentDate, " ")(1))
        d2 = TimeValue(L_CurrentStartTime)
        If d1 = d2 Then
            MsgBox "Same Time"
        End If
    End Sub
    
  • 2

    很奇怪你'd have to split the date out to make it work. A solution is a solution, so @Gary'的学生已经提供了让你前进的答案 . 但如果为什么会折磨你(就像我一样),你必须分享更多的过程 . 例如,我将两个样本 17/03/2014 2:05:002:05:00 作为文本粘贴到工作簿的单元格 B2B3 中,然后执行以下操作:

    Sub Macro1()
    
    Dim C_CurrentDate As Date
    C_CurrentDate = CDate(Range("B2").Value)
    Dim L_CurrentStartTime As Date
    L_CurrentStartTime = CDate(Range("B3").Value)
    
    Debug.Print C_CurrentDate
    Debug.Print CDate(Range("B2").Value)
    Debug.Print TimeValue(Range("B2").Value)
    
    Debug.Print L_CurrentStartTime
    Debug.Print CDate(Range("B3").Value)
    
    If TimeValue(Range("B2").Value) = CDate(Range("B3").Value) Then
        Debug.Print "True"
    End If
    
    If TimeValue(C_CurrentDate) = L_CurrentStartTime Then
        Debug.Print "True"
    End If
    
    
    End Sub
    

    我的两个 If 语句都解析为 True ,听起来你正在做的事情,我们或许可以帮助你找出原因 . 当然,没有保证 . :)

相关问题