VBA中的date/时间比较

目标:Excel工作表包含一系列活动。 目标是比较两个活动的date/时间。 我需要确定两者之间是否有重叠。 B列包含每个活动的开始date和时间,C列包含每个活动的结束date和时间。

ActivityOneStartTime = Range("B41").Value ActivityOneEndTime = Range("C41").Value ActivityTwoStartTime = Range("B32").Value ActivityTwoEndTime = Range("C32").Value If ActivityOneStartTime >= ActivityTwoStartTime Then If ActivityOneStartTime < ActivityTwoEndTime Then booScheduleConflict = True End If End If If ActivityOneEndTime <= ActivityTwoEndTime Then If ActivityOneEndTime > ActivityTwoStartTime Then booScheduleConflict = True End If End If 

以上这些当然是行不通的。 所以,在尝试了其他一些不成功的方法后,我开始通过比较第一年,然后几个月,然后几天,然后几小时,然后几分钟,设置案例的步骤,但我相信有一个更简单的方法。

预先感谢您对这一挑战的任何帮助。

喜欢这个:

 ActivityOneStartTime = Range("B41").Value ActivityOneEndTime = Range("C41").Value ActivityTwoStartTime = Range("B32").Value ActivityTwoEndTime = Range("C32").Value If ActivityOneStartTime < ActivityTwoEndTime Then If ActivityOneEndTime > ActivityTwoStartTime Then booScheduleConflict = True End If End If 

我认为你的问题是确定testing重叠的逻辑。

尝试这个

 booScheduleConflict = Not(ActivityOneEndTime <= ActivityTwoStartTime or _ ActivityOneStartTime >= ActivityTwoEndTime) 

它可以通过使用TimeValue属性来完成。 这是一个例子:

 Dim date1 As Date Dim date2 As Date Dim date3 As Date date1 = TimeValue(Range("A1").Text) date2 = TimeValue(Range("B1").Text) date3 = TimeValue(Range("C1").Text) If date3 >= date1 And date3 <= date2 Then 'Yes! Else 'No! End If