Excel VBA相等时间不匹配

我在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

它们的区别在于E-17的范围。

这怎么可能? 这两个值都是从单元格数据中读取的。

只要放弃组合DateTime的date部分:

 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 

很奇怪你不得不把date分开才能工作。 一个解决scheme是一个解决scheme,所以@加里的学生提供了答案,可以让你前进。 但如果为什么要折磨你(就像我),你将不得不分享更多的stream程。 例如,我拿了你的两个样本, 17/03/2014 2:05:00 / 2:05:00 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语句都parsing为True ,并且听起来就像基本上以同样的方式获取值。 如果我们可以看到更多的你在做什么,我们可以帮助你找出原因。 当然,没有保证。 🙂