Excel VBA搜索范围取决于一天中的时间

时间:2014-12-11 10:17:02

标签: excel excel-vba vba

我有一列格式为“dd / mm / yy HH:MM:SS”的单元格,我想要计算具有以下范围内的日期和时间的单元格数量,具体取决于时间一天。

如果当前时间是< 07:00然后

Count Occurances in range between 07:00 the previous day and now

否则

Count occurances between 07:00 today and now

结束如果

提前谢谢。

1 个答案:

答案 0 :(得分:0)

此代码很可能适合您。它也很简单,很容易改变,以引用你需要它看的正确的纸张和单元格。我希望这有帮助!

Sub CountingNumberOfOccurancesWithingRangeDependingOnTime()
    Dim curTime As Date
    Dim preTime As Date
    Dim todayTime As Date
    Dim curHour As Integer
    Dim counter As Integer

    curTime = Now
    curHour = Format(curTime, "HH")
    preTime = curTime - 1

    x = 1

    If curHour < 7 Then
        Do Until Sheet1.Cells(x, 1).Value = Empty
            cellTime = Sheet1.Cells(x, 1).Value

            If cellTime > preTime And cellTime < curTime Then
                counter = counter + 1
            End If
            x = x + 1
        Loop
    Else
        todayTime = Date & " " & "07:00:00"
        Do Until Sheet1.Cells(x, 1).Value = Empty
            cellTime = Sheet1.Cells(x, 1).Value

            If cellTime > todayTime And cellTime < curTime Then
                counter = counter + 1
            End If
            x = x + 1
        Loop
    End If

    MsgBox counter 'This isn't necissary, but it just is here to show the number of cells counted



End Sub