Search code examples
vbaexceldatevb6

Subtract a specified number of hours from a given date/time to get a new date/time


I'm trying to figure out how to calculate a date/time by subtracting a given number of hours from a given due date/time, so that I know when I need to start a process step on a product component in order to have it finished in time to ship to the customer.

For example, the product needs to be ready to ship to the customer by 15:00 on September 15, 2017

The final assembly and verification steps, from last to first, are

  • Step 15 - requires 12.6 hours to complete
  • Step 10 - requires 32.1 hours to complete
  • Step 05 - requires 25.9 hours to complete

working backwards

  • step 15 would need to be complete by 15:00 on 9/15/2017 to ship to customer
  • step 10 would need to be complete by 02:24 on 9/15/2017 to start step 15 on time
  • step 05 would need to be complete by 06:18 on 9/13/2017 to start step 10 on time
  • All components would need to be ready for assembly by 04:24 on 9/12/2017 to start step 05 on time

I've spent the day searching for an example that would be close enough to what I want and I think I will have to do something with the DateTime function, I'm just not sure what at the moment


Solution

  • You can subtract n hours from a date by simply subtracting n/24 from it. You can also use the TimeSerial function to subtract hours, minutes and seconds. This example illustrates the two methods, it subtracts 1 hour and a half from the current time using the two methods.

    Sub substractDates()
      Dim d1 As Date, d2 As Date, d3 as Date
      d1 = Now()
      d2 = d1 - TimeSerial(1, 30, 0)
      d3 = d1 - 1.5 / 24
      Debug.Print d1, d2, d3
    End Sub
    

    p.s. yet a third way is to use TimeValue("1:30:0") which is equivalent to TimeSerial(1, 30, 0).