VBA如果时间介于两次之间

时间:2012-02-16 20:58:39

标签: vba date time compare

i = 1    
For Each cell In Range("D1:D10000")
  If IsEmpty(cell.Value) Then Exit For

  Select Case Range("N" & i).Value
    Case 0 To 40
      startTime  = "13:00"
    Case 40 To 60
      secondTime = Range("V" & i).Value
    Case 60 To 100
      finalTime = Range("V" & i).Value
    Case Else

   End Select

  Dim startTime As Date
  Dim secondTime As Date
  Dim finalTime As Date
  Dim timeRef As Date
  timeRef = Range("V" & i).Value

  If timeRef >= startTime And timeRef < secondTime Then 

  ElseIf timeRef >= secondTime And timeRef < finalTime Then

  ElseIf timeRef > finalTime Then

  End If
  i = i + 1
Next

好的,我正在使用上面的内容来尝试比较格式化为日期的时间。它们都是从自定义格式化为“hh:mm”的工作表中获取的,但除了最终的elseif

之外我似乎无法进入任何时间。

哎呀!

1 个答案:

答案 0 :(得分:1)

您在分配给他们之后声明了这些值(startTimesecondTimefinalTime)。至少,您需要更改代码以声明然后分配。 (另外,你的第一个if语句是错误的;第一个测试应该只是If timeRef < secondTime。)

' Declare variables before assigning values to them
Dim startTime As Date
Dim secondTime As Date
Dim finalTime As Date
Dim timeRef As Date

i = 1    
For Each cell In Range("D1:D10000")
  If IsEmpty(cell.Value) Then Exit For

  Select Case Range("N" & i).Value
    Case 0 To 40
      startTime  = "13:00"
    Case 40 To 60
      secondTime = Range("V" & i).Value
    Case 60 To 100
      finalTime = Range("V" & i).Value
    Case Else
      ' You should do something here; what if the cell is empty or invalid?
      ' You end up with no value assigned to anything when leaving the Select
   End Select

  timeRef = Range("V" & i).Value

  If timeRef < secondTime Then 

  ElseIf timeRef >= secondTime And timeRef < finalTime Then

  ElseIf timeRef > finalTime Then

  End If
  i = i + 1
Next

由于我没有任何数据需要测试,我不知道这是否真的有效,但它修复了阻止工作的明显问题。