我正在创建一个显示前一个班次数据的程序:共有3个班次:班次1:上午6点到下午2点班次2:下午2点到晚上10点班次3:晚上10点到早上6点所以视当前时间而定我应该能够复制前一班的所有数据。
在过去的一周里,我一直在努力破坏我的大脑,直到现在还没有运气,程序运行正常,但我觉得逻辑不对。我也得到其他数据,这不属于前一班次。
以下是仅包含逻辑的摘录:非常感谢您的帮助!
For i = lastrow1 To (lastrow1 - 150) Step -1
mydate = Sheets("Summary").Cells(i, "A").Value
mytime = Sheets("Summary").Cells(i, "B").Value
mystatus = Sheets("Summary").Cells(i, "J").Value
Sheets("Previousshiftdata").Activate
lastrow2 = Sheets("Previousshiftdata").Range("A" & Rows.Count).End(xlUp).Row
'j indicates destination row no i.e. row no. in previoushift
j = lastrow2 + 1
'to get shift 3 data
If (x = "Shift 3" And (mydate = Date - 1 And mytime > TimeValue("22:00:00"))) Or (mydate = Date And mytime > TimeValue("00:00:00") And mytime < TimeValue("6:00:00")) Then
Sheets("Summary").Activate
Sheets("Summary").Range(Cells(i, "A"), Cells(i, "J")).Copy
Sheets("Previousshiftdata").Activate
Sheets("Previousshiftdata").Range(Cells(j, "A"), Cells(j, "J")).Select
Selection.PasteSpecial Paste:=xlPasteValues
'to get shift 2 data
ElseIf ((mydate = Date) And (mytime > TimeValue("14:00:00")) And (mytime < TimeValue("22:00:00"))) Or ((mydate = Date - 1) And (mytime > TimeValue("14:00:00")) And (mytime < TimeValue("22:00:00"))) Then
Sheets("Summary").Activate
Sheets("Summary").Range(Cells(i, "A"), Cells(i, "J")).Copy
Sheets("Previousshiftdata").Activate
Sheets("Previousshiftdata").Range(Cells(j, "A"), Cells(j, "J")).Select
Selection.PasteSpecial Paste:=xlPasteValues
'to get shift 1 data
ElseIf (TimeValue("6:00:00") < mytime < TimeValue("14:00:00")) And (mydate = Date) Then
Sheets("Summary").Activate
Sheets("Summary").Range(Cells(i, "A"), Cells(i, "J")).Copy
Sheets("Previousshiftdata").Activate
Sheets("Previousshiftdata").Range(Cells(j, "A"), Cells(j, "J")).Select
Selection.PasteSpecial Paste:=xlPasteValues
End If
'to clear clipboard
Application.CutCopyMode = False
Next i
Sheets("Previousstatus").Activate
End Sub
TimeValue("6:00:00") < mytime < TimeValue("14:00:00")
VBA不像你期望的那样处理这个问题。如果你想做那样的事情,那么你需要这样做:
TimeValue("6:00:00") < mytime AND mytime < TimeValue("14:00:00")
我给你的建议是做一个小功能,检查一个给定的时间是否在两次之间:
Private Function isTimeBetween(timeToCheck As Date, shiftStartTime As String, shiftEndTime As String)
Dim shiftStartTime2 As Date
Dim shiftEndTime2 As Date
shiftStartTime2 = TimeValue(shiftStartTime)
shiftEndTime2 = TimeValue(shiftEndTime)
If shiftStartTime2 < timeToCheck And timeToCheck < shiftEndTime2 Then
isTimeBetween = True
Else
isTimeBetween = False
End If
End Function
使用如下:
Dim mytime As Date
mytime = TimeValue("10:00:00")
isTimeBetween(mytime, "6:00:00", "14:00:00")
...返回True。它将清理你的代码以将其分解为更小的函数。