Hour VBA function – How to get hour from date and time

Last Updated on January 11, 2023 by token

1. Hour VBA function – Description

The Hour VBA function   returns a number representing the hour for a given date and time. So if we want Excel VBA to return to us numbers corresponding to the following hours, we should use this function for this purpose. Please note that the date and time from which we want to obtain the number of hours should be taken from the variable or saved in the VB code in the time or date and time format, i.e.  YYYY-MM-DD HH24: MI: SS or #HH: MM: SS [ P / A] M # . The function returns a numeric value between 0 and 23.

2. VBA Hour Function – Syntax

Hour (Time)

Time : The time from which we want to get the next number corresponding to the number of hours.

Function return:  Integer / Numeric value. Value in the range 0-23.

3. VBA Hour function – Example

How to use the Hour function in VBA Excel? The following are examples of using the Hour function in the VisualBasic Editor.

Example 1:

Sub HourFunctionExample1 ()

MsgBox Hour (# 22: 35: 17 #)
MsgBox Hour (# 2018-07-31 22:35:17 #)
MsgBox Hour (# 4: 35: 17 AM #)
MsgBox Hour (# 1/1/2019 11:15:59 PM #)

End Sub

Example 2:

Sub HourFunctionExample2 ()

Dim DatDate As Date
DatDate = # 4: 35: 17 AM #
MsgBox Hour (DatDate)

End Sub

Example 3:

Sub HourFunctionExample3 ()

Range ("A1") = Hour (# 22: 35: 17 #) 
Range ("A2") = Hour (# 2018-07-31 22:35:17 #) 
Range ("A3") = Hour (# 4: 35: 17 AM #) 
Range ("A4") = Hour (# 1/1/2019 11:15:59 PM #)

End Sub
Excel VBA functions - Hour VBA function
Excel VBA functions – Hour VBA function

4. VB Hour Function – Additional information

  • Date / Time from which we want to obtain a number corresponding to the time should have the Date data type   or be written in the format # YYYY-MM-DD HH24: MI: SS #, #HH: MM: SS [P / A] M # or # HH24 : MI: SS #

5. Hour VisualBasic – Where to use?

The function can be used in: Excel 2003, Excel 2007, Excel 2010, Excel 2013, Excel 2016, Excel 2019, Excel 2021, Excel 365.

The article is part of the VBA Excel function list. You can find a list of all VBA functions at this address:  VBA functions .

Leave a comment

Your email address will not be published. Required fields are marked *

%d bloggers like this: