简体   繁体   中英

Excel VBA Time and Date

I am trying to figure out how to alter this code so that it will work for what I need. I want to basically say that if today is Friday and the time is 4:00PM or greater, then the new time is Monday 7:00AM. Here is what I have but I cannot figure out the TIME part of it.

modDropOff = Now
LHour = Hour("4:00:00 PM")
LNewHour = Hour("07:00:00 AM")

If Weekday(Date) = vbFriday And Now() >= LHour Then
modDropOff = Date + 3 <<< + LNewHour
End If

This is a bit long-winded, but seems to work:

If Weekday(modDropOff) = 6 And Hour(modDropOff) >= 16 Then
    modDropOff = DateSerial(Year(modDropOff), Month(modDropOff), Day(modDropOff)) + 3 + TimeSerial(7, 0, 0)
End If

Some ways to edit dates:

Option Explicit

Public Sub checkDate()

    Dim modDropOff As Date

    If Weekday(Now) = 2 And Hour(Now) >= 16 Then

        modDropOff = (Date + 3) + TimeValue("07:00:00 AM")

    Else

        modDropOff = Now

    End If

    MsgBox Format(modDropOff, "ddd mmm dd, yyyy - hh:mm:ss AMPM")

End Sub

Public Sub editDate()
    Dim modDropOff As Date
    If Weekday(Now) = 2 And Hour(Now) >= 16 Then
        modDropOff = DateAdd("d", 3, Now)
        modDropOff = DateSerial(Year(Now), Month(Now), Day(Now) + 3) + TimeSerial(7, 0, 0)
    Else
        modDropOff = Time
    End If
    MsgBox Format(xDate, "ddd mmm dd, yyyy - hh:mm:ss AMPM")
End Sub

.

Other VBA Date and Time functions

  • Date - current system Date (Date part only)
  • Now - current system Date and Time
  • Year, Month, MonthName, WeekDay, WeekdayName, Day
  • Hour, Minute, Second
  • IsDate, CDate, DateSerial, DateValue, DateAdd, DateDiff, DatePart
  • Time, TimeSerial, TimeValue
  • FormatDateTime, Timer

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM