Checking if Datetime is in between a given Datetim

2019-08-21 08:01发布

I have a table which looks like this: enter image description here

What I am trying to do is to sum up a few values within a given datetime range. Let's say for example between 01.01.2016 00:30 and 01.01.2016 02:00.

My if clause looks like this.

If .Cells(i, 3).Value = "Samariter" And .Cells(i, 1).Value >= "01.01.2016 00:30:00" And .Cells(i, 1).Value <= "01.01.2016 02:00:00" Then

And if I run the algorithm, it runs correctly, BUT:

If I try, for example, the range from 25.1.2016 20:00 until 26.1.2016 02:00:

enter image description here

This is my if clause again:

If .Cells(i, 3).Value = "Samariter" And .Cells(i, 1).Value >= "25.01.2016 20:00:00" And .Cells(i, 1).Value <= "26.01.2016 02:00:00" Then

If I run this, it will start at the correct line, but will exceed the upper bound of the datetime interval.

What is the problem here?

1条回答
爷的心禁止访问
2楼-- · 2019-08-21 08:17

Xabier's answer solved the problem, the if-clause should look like this in order for the algorithm to run properly:

If .Cells(i, 3).Value = "Samariter" And DateDiff("s", .Cells(i, 1).Value, "25.01.2016 00:00:00") < 0 And DateDiff("s", .Cells(i, 1).Value, "31.01.2016 23:59:59") >= 0 Then
查看更多
登录 后发表回答