[英]Random date-time between two date-times in Excel VBA
How can I get a random date-time between two date-times in Excel VBA? 如何在Excel VBA中的两个日期之间获得随机日期时间?
I tried 我试过了
worksheetFunction.Randbetween(time1, time2)
but that only delivers the date without hours, minutes and seconds (although time1
and time2
are including hours, minutes and seconds) 但是只提供没有小时,分钟和秒的日期(尽管
time1
和time2
包括小时,分钟和秒)
I also tried the following code where I declared tmp as string. 我还尝试了以下代码,我将tmp声明为字符串。
tmp = DateDiff("s", time1, time2) [to get the seconds]
tmp = Int((tmp +1) * Rnd) [to get a random number inbetween the DateDiff]
tmp = tmp + CDbl(time1)
But that also doesn't work... 但那也行不通......
The following code should do the trick: 以下代码应该可以解决问题:
worksheetFunction.Randbetween(time1, time2) + Rnd()
Rnd() will generate a value between 0 and 1, and time is stored as a fraction of a day Rnd()将生成一个介于0和1之间的值,并将时间存储为一天的一小部分
You can also avoid the first part and use 您也可以避开第一部分并使用
time1+Rnd()*(time2-time1+1)
Remove +1
if you want time2 '00:00:00' to be the upper limit, or if both time1
and time2
are datetimes, not dates 如果你想将time2 '00:00:00'作为上限,或者如果
time1
和time2
都是日期时间,则不删除+1
You should also use Randomize
statement before using both versions. 在使用这两个版本之前,您还应该使用
Randomize
语句。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.