在比较日期范围时遇到问题

时间:2017-08-31 07:43:33

标签: excel vba excel-vba

我从单独的工作表中提取日期但是在使用if语句时结果是错误的但日期是否正确?

Dim tacholine, cal_line As Long
Dim tachodate, calstartdate, calenddate As Date


cal_line = 1
'next calender line
cal_line = cal_line + 1

For tacholine = 1 To 842
'check Week 1
tachodate = Format(Worksheets("All Workers").Range("d" & tacholine), "dd/mm/yyyy")
calstartdate = Format(Worksheets("Calender").Range("b" & cal_line), "dd/mm/yyyy")
calenddate = Format(Worksheets("Calender").Range("c" & cal_line), "dd/mm/yyyy")

If tachodate >= calstartdate And tachodate <= calenddate Then
  Application.StatusBar = "Match found : " & tachodate & " between dates " & calstartdate & " and " & calenddate
  Worksheets("All Workers").Range("u" & tacholine).Value = Worksheets("Calender").Range("A" & cal_line)
End If

Next tacholine

1 个答案:

答案 0 :(得分:0)

如果要在一行上声明多个变量,请确保具体声明每个变量,即

Dim tachodate, calstartdate, calenddate As Date

应该是

 Dim tachodate As Date, calstartdate As Date, calenddate As Date

在VBA中,Dim tachodate, calstartdate, calenddate As Date表示只有calenddate被声明为日期而tachodate, calstartdate被视为变体。

可以尝试

Dim tacholine, cal_line As Long
'declare all variables separately
Dim tachodate As Date, calstartdate As Date, calenddate As Date

cal_line = 1
'next calender line
'cal_line = cal_line + 1    'moved inside loop

For tacholine = 1 To 842

cal_line = cal_line + 1
'check Week 1
tachodate = Format(Worksheets("All Workers").Range("d" & tacholine), "dd/mm/yyyy")
calstartdate = Format(Worksheets("Calender").Range("b" & cal_line), "dd/mm/yyyy")
calenddate = Format(Worksheets("Calender").Range("c" & cal_line), "dd/mm/yyyy")

If tachodate >= calstartdate And tachodate <= calenddate Then
  Application.StatusBar = "Match found : " & tachodate & " between dates " & calstartdate & " and " & calenddate
  Worksheets("All Workers").Range("u" & tacholine).Value = Worksheets("Calender").Range("A" & cal_line)
End If

Next tacholine