Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Excel VBA Adding 1 hour to a date / time string

I have a text string that looks like this: "06/10/15 4:53pm". I want to add 1 hour (60 minutes exactly) to the text string looks like this: "06/10/15 5:53pm"

Any suggestions would be appreciated.

like image 345
Shaves Avatar asked Jul 15 '15 19:07

Shaves


People also ask

How do I add hours in VBA?

Dateadd vba function The x function is used to perform time arithmetic in Excel VBA. With the Dateadd function, you can add not only hours, but also year, quarter, month, day of the year, day, day of the week, week, minute, second. The format of the interval in the dateadd function is: yyyy Year.

How do I add a time delay to a macro in Excel?

Use the VBA Application. Wait method to pause your macro for a specific amount of time. Application. Wait is a simple way to delay your macro by a fixed number of seconds.

How do I convert a date to a string in Excel VBA?

Say that in the first column, A, you have data of the type 2016/03/25 21:20:00 but is stored as text. Then in column B write =DATEVALUE(A1) and in column C write =TIMEVALUE(A1) . Then in column D do =B1+C1 to add the numerical formats of the date and time.

How do you declare a time variable in VBA?

First, we have declared the variable “MyTime” as a date. Then, we assign the value to the variable by applying TimeValue. Then in the message box, we have assigned the variable result. MsgBox "Supplied Time is: " & MyTime, vbInformation, "TIMEVALUE Function".


2 Answers

Convert it to a date, add an hour, and convert back to string using format

Private Sub TestIt()

    MsgBox AddHour("06/10/15 4:53pm")

End Sub

Public Function AddHour(ByVal sTime As String) As String
    Dim dt As Date

    dt = CDate(sTime)
    dt = DateAdd("h", 1, dt)

    AddHour = Format(dt, "mm/dd/yy h:nnam/pm")

End Function

Reference:

  • VBA CDate Function
  • VBA DateAdd Function
  • VBA Format Function
like image 87
Don Jewett Avatar answered Nov 05 '22 14:11

Don Jewett


No VBA needed...assuming the time value above(06/10/15 4:53pm) is in cell A1 the Formula you are looking for is:

=A1+TIME(1,0,0)
like image 44
gokool108 Avatar answered Nov 05 '22 12:11

gokool108