Word vba формат даты

Word VBA, Date Format

Jun 27, 2015 in Date

When writing dates to a word document you could specify a specific format. For example consider the code below:

Sub main()
Range.Text = Date
End Sub

It prints the current date to the document:

Word VBA, Date
We can change the way the date is output using the code below:

Sub example2()
Range.Text = Format(Date, "MMMM DD, YYYY ")
End Sub

Result:

Word VBA, Date, Format

In the table below you can see the result of using different formattings for outputting date values:

Format Result
MMMM DD, YYYY May 05, 2014
MM DD, YYYY 05 05, 2014
M D, YYYY 5 05, 2014
MMMM D, YYYY May 5, 2014
MMMM D, YY May 5, 14
DDDD MMMM DD, YYYY Monday May 5, 14
DD MMMM DDDD, YY 05 May Monday, 14
YYYY, MMMM, DD 2014, May, 05

See also:

  • Word VBA, Go to Specific Line
  • Word VBA Bookmarks

If you need assistance with your code, or you are looking for a VBA programmer to hire feel free to contact me. Also please visit my website  www.software-solutions-online.com

title keywords f1_keywords ms.prod ms.assetid ms.date ms.localizationpriority

Format function (Visual Basic for Applications)

vblr6.chm1008925

vblr6.chm1008925

office

67f60abf-0c77-49ec-924f-74ae6eb96ea8

08/14/2019

high

Returns a Variant (String) containing an expression formatted according to instructions contained in a format expression.

[!includeAdd-ins note]

Syntax

Format(Expression, [ Format ], [ FirstDayOfWeek ], [ FirstWeekOfYear ])

The Format function syntax has these parts.

Part Description
Expression Required. Any valid expression.
Format Optional. A valid named or user-defined format expression.
FirstDayOfWeek Optional. A constant that specifies the first day of the week.
FirstWeekOfYear Optional. A constant that specifies the first week of the year.

Settings

The firstdayofweek argument has these settings.

Constant Value Description
vbUseSystem 0 Use NLS API setting.
vbSunday 1 Sunday (default)
vbMonday 2 Monday
vbTuesday 3 Tuesday
vbWednesday 4 Wednesday
vbThursday 5 Thursday
vbFriday 6 Friday
vbSaturday 7 Saturday

The firstweekofyear argument has these settings.

Constant Value Description
vbUseSystem 0 Use NLS API setting.
vbFirstJan1 1 Start with week in which January 1 occurs (default).
vbFirstFourDays 2 Start with the first week that has at least four days in the year.
vbFirstFullWeek 3 Start with the first full week of the year.

Remarks

To format Do this
Numbers Use predefined named numeric formats or create user-defined numeric formats.
Dates and times Use predefined named date/time formats or create user-defined date/time formats.
Date and time serial numbers Use date and time formats or numeric formats.
Strings Create your own user-defined string formats.

Format truncates format to 257 characters.

If you try to format a number without specifying format, Format provides functionality similar to the Str function, although it is internationally aware. However, positive numbers formatted as strings using Format don’t include a leading space reserved for the sign of the value; those converted using Str retain the leading space.

If you are formatting a non-localized numeric string, you should use a user-defined numeric format to ensure that you get the look you want.

[!NOTE]
If the Calendar property setting is Gregorian and format specifies date formatting, the supplied expression must be Gregorian. If the Visual Basic Calendar property setting is Hijri, the supplied expression must be Hijri.

If the calendar is Gregorian, the meaning of format expression symbols is unchanged. If the calendar is Hijri, all date format symbols (for example, dddd, mmmm, yyyy ) have the same meaning but apply to the Hijri calendar. Format symbols remain in English; symbols that result in text display (for example, AM and PM) display the string (English or Arabic) associated with that symbol. The range of certain symbols changes when the calendar is Hijri.

Date symbols

Symbol Range
d 1-31 (Day of month, with no leading zero)
dd 01-31 (Day of month, with a leading zero)
w 1-7 (Day of week, starting with Sunday = 1)
ww 1-53 (Week of year, with no leading zero; Week 1 starts on Jan 1)
m 1-12 (Month of year, with no leading zero, starting with January = 1)
mm 01-12 (Month of year, with a leading zero, starting with January = 01)
mmm Displays abbreviated month names (Hijri month names have no abbreviations)
mmmm Displays full month names
y 1-366 (Day of year)
yy 00-99 (Last two digits of year)
yyyy 100-9999 (Three- or Four-digit year)

Time symbols

Symbol Range
h 0-23 (1-12 with «AM» or «PM» appended) (Hour of day, with no leading zero)
hh 00-23 (01-12 with «AM» or «PM» appended) (Hour of day, with a leading zero)
n 0-59 (Minute of hour, with no leading zero)
nn 00-59 (Minute of hour, with a leading zero)
m 0-59 (Minute of hour, with no leading zero). Only if preceded by h or hh
mm 00-59 (Minute of hour, with a leading zero). Only if preceded by h or hh
s 0-59 (Second of minute, with no leading zero)
ss 00-59 (Second of minute, with a leading zero)

Example

This example shows various uses of the Format function to format values using both named formats and user-defined formats. For the date separator (/), time separator (:), and AM/ PM literal, the actual formatted output displayed by your system depends on the locale settings on which the code is running. When times and dates are displayed in the development environment, the short time format and short date format of the code locale are used. When displayed by running code, the short time format and short date format of the system locale are used, which may differ from the code locale. For this example, English/U.S. is assumed. MyTime and MyDate are displayed in the development environment using current system short time setting and short date setting.

Dim MyTime, MyDate, MyStr
MyTime = #17:04:23#
MyDate = #January 27, 1993#

' Returns current system time in the system-defined long time format.
MyStr = Format(Time, "Long Time")

' Returns current system date in the system-defined long date format.
MyStr = Format(Date, "Long Date")

MyStr = Format(MyTime, "h:m:s")    ' Returns "17:4:23".
MyStr = Format(MyTime, "hh:mm:ss am/pm")    ' Returns "05:04:23 pm".
MyStr = Format(MyTime, "hh:mm:ss AM/PM")    ' Returns "05:04:23 PM".
MyStr = Format(MyDate, "dddd, mmm d yyyy")    ' Returns "Wednesday, Jan 27 1993".
' If format is not supplied, a string is returned.
MyStr = Format(23)    ' Returns "23".

' User-defined formats.
MyStr = Format(5459.4, "##,##0.00")    ' Returns "5,459.40".
MyStr = Format(334.9, "###0.00")    ' Returns "334.90".
MyStr = Format(5, "0.00%")    ' Returns "500.00%".
MyStr = Format("HELLO", "<")    ' Returns "hello".
MyStr = Format("This is it", ">")    ' Returns "THIS IS IT".

Different formats for different numeric values

A user-defined format expression for numbers can have from one to four sections separated by semicolons. If the format argument contains one of the named numeric formats, only one section is allowed.

If you use The result is
One section only The format expression applies to all values.
Two sections The first section applies to positive values and zeros, the second to negative values.
Three sections The first section applies to positive values, the second to negative values, and the third to zeros.
Four sections The first section applies to positive values, the second to negative values, the third to zeros, and the fourth to Null values.

If you include semicolons with nothing between them, the missing section is printed using the format of the positive value. For example, the following format displays positive and negative values using the format in the first section and displays «Zero» if the value is zero.

Different formats for different string values

A format expression for strings can have one section or two sections separated by a semicolon (;).

If you use The result is
One section only The format applies to all string data.
Two sections The first section applies to string data, the second to Null values and zero-length strings («»).

Named date/time formats

The following table identifies the predefined date and time format names.

Format name Description
General Date Display a date and/or time, for example, 4/3/93 05:34 PM. If there is no fractional part, display only a date, for example, 4/3/93. If there is no integer part, display time only, for example, 05:34 PM. Date display is determined by your system settings.
Long Date Display a date according to your system’s long date format.
Medium Date Display a date using the medium date format appropriate for the language version of the host application.
Short Date Display a date using your system’s short date format.
Long Time Display a time using your system’s long time format; includes hours, minutes, seconds.
Medium Time Display time in 12-hour format using hours and minutes and the AM/PM designator.
Short Time Display a time using the 24-hour format, for example, 17:45.

Named numeric formats

The following table identifies the predefined numeric format names.

Format name Description
General Number Display number with no thousand separator.
Currency Display number with thousand separator, if appropriate; display two digits to the right of the decimal separator. Output is based on system locale settings.
Fixed Display at least one digit to the left and two digits to the right of the decimal separator.
Standard Display number with thousand separator, at least one digit to the left and two digits to the right of the decimal separator.
Percent Display number multiplied by 100 with a percent sign (%) appended to the right; always display two digits to the right of the decimal separator.
Scientific Use standard scientific notation.
Yes/No Display No if number is 0; otherwise, display Yes.
True/False Display False if number is 0; otherwise, display True.
On/Off Display Off if number is 0; otherwise, display On.

User-defined string formats

Use any of the following characters to create a format expression for strings.

Character Description
@ Character placeholder. Display a character or a space. If the string has a character in the position where the at symbol (@) appears in the format string, display it; otherwise, display a space in that position. Placeholders are filled from right to left unless there is an exclamation point character (!) in the format string.
& Character placeholder. Display a character or nothing. If the string has a character in the position where the ampersand (&) appears, display it; otherwise, display nothing. Placeholders are filled from right to left unless there is an exclamation point character (!) in the format string.
< Force lowercase. Display all characters in lowercase format.
> Force uppercase. Display all characters in uppercase format.
! Force left to right fill of placeholders. The default is to fill placeholders from right to left.

User-defined date/time formats

The following table identifies characters you can use to create user-defined date/time formats.

Character Description
(:) Time separator. In some locales, other characters may be used to represent the time separator. The time separator separates hours, minutes, and seconds when time values are formatted. The actual character used as the time separator in formatted output is determined by your system settings.
(/) Date separator. In some locales, other characters may be used to represent the date separator. The date separator separates the day, month, and year when date values are formatted. The actual character used as the date separator in formatted output is determined by your system settings.
c Display the date as ddddd and display the time as ttttt, in that order. Display only date information if there is no fractional part to the date serial number; display only time information if there is no integer portion.
d Display the day as a number without a leading zero (1–31).
dd Display the day as a number with a leading zero (01–31).
ddd Display the day as an abbreviation (Sun–Sat). Localized.
dddd Display the day as a full name (Sunday–Saturday). Localized.
ddddd Display the date as a complete date (including day, month, and year), formatted according to your system’s short date format setting. The default short date format is m/d/yy.
dddddd Display a date serial number as a complete date (including day, month, and year) formatted according to the long date setting recognized by your system. The default long date format is mmmm dd, yyyy.
w Display the day of the week as a number (1 for Sunday through 7 for Saturday).
ww Display the week of the year as a number (1–54).
m Display the month as a number without a leading zero (1–12). If m immediately follows h or hh, the minute rather than the month is displayed.
mm Display the month as a number with a leading zero (01–12). If m immediately follows h or hh, the minute rather than the month is displayed.
mmm Display the month as an abbreviation (Jan–Dec). Localized.
mmmm Display the month as a full month name (January–December). Localized.
q Display the quarter of the year as a number (1–4).
y Display the day of the year as a number (1–366).
yy Display the year as a 2-digit number (00–99).
yyyy Display the year as a 4-digit number (100–9999).
h Display the hour as a number without a leading zero (0–23).
hh Display the hour as a number with a leading zero (00–23).
n Display the minute as a number without a leading zero (0–59).
nn Display the minute as a number with a leading zero (00–59).
s Display the second as a number without a leading zero (0–59).
ss Display the second as a number with a leading zero (00–59).
ttttt Display a time as a complete time (including hour, minute, and second), formatted using the time separator defined by the time format recognized by your system. A leading zero is displayed if the leading zero option is selected and the time is before 10:00 A.M. or P.M. The default time format is h:mm:ss.
AM/PM Use the 12-hour clock and display an uppercase AM with any hour before noon; display an uppercase PM with any hour between noon and 11:59 P.M.
am/pm Use the 12-hour clock and display a lowercase AM with any hour before noon; display a lowercase PM with any hour between noon and 11:59 P.M.
A/P Use the 12-hour clock and display an uppercase A with any hour before noon; display an uppercase P with any hour between noon and 11:59 P.M.
a/p Use the 12-hour clock and display a lowercase A with any hour before noon; display a lowercase P with any hour between noon and 11:59 P.M.
AMPM Use the 12-hour clock and display the AM string literal as defined by your system with any hour before noon; display the PM string literal as defined by your system with any hour between noon and 11:59 P.M. AMPM can be either uppercase or lowercase, but the case of the string displayed matches the string as defined by your system settings. The default format is AM/PM. If your system is set to 24-hour clock, the string is typical set to a zero-length string.

User-defined numeric formats

The following table identifies characters you can use to create user-defined number formats.

Character Description
None Display the number with no formatting.
(0) Digit placeholder. Display a digit or a zero. If the expression has a digit in the position where the 0 appears in the format string, display it; otherwise, display a zero in that position.If the number has fewer digits than there are zeros (on either side of the decimal) in the format expression, display leading or trailing zeros. If the number has more digits to the right of the decimal separator than there are zeros to the right of the decimal separator in the format expression, round the number to as many decimal places as there are zeros. If the number has more digits to the left of the decimal separator than there are zeros to the left of the decimal separator in the format expression, display the extra digits without modification.
(#) Digit placeholder. Display a digit or nothing. If the expression has a digit in the position where the # appears in the format string, display it; otherwise, display nothing in that position. This symbol works like the 0 digit placeholder, except that leading and trailing zeros aren’t displayed if the number has the same or fewer digits than there are # characters on either side of the decimal separator in the format expression.
(.) Decimal placeholder. In some locales, a comma is used as the decimal separator. The decimal placeholder determines how many digits are displayed to the left and right of the decimal separator. If the format expression contains only number signs to the left of this symbol, numbers smaller than 1 begin with a decimal separator. To display a leading zero displayed with fractional numbers, use 0 as the first digit placeholder to the left of the decimal separator. The actual character used as a decimal placeholder in the formatted output depends on the Number Format recognized by your system.
(%) Percentage placeholder. The expression is multiplied by 100. The percent character (%) is inserted in the position where it appears in the format string.
(,) Thousand separator. In some locales, a period is used as a thousand separator. The thousand separator separates thousands from hundreds within a number that has four or more places to the left of the decimal separator. Standard use of the thousand separator is specified if the format contains a thousand separator surrounded by digit placeholders (0 or #). Two adjacent thousand separators or a thousand separator immediately to the left of the decimal separator (whether or not a decimal is specified) means «scale the number by dividing it by 1000, rounding as needed.» For example, you can use the format string «##0,,» to represent 100 million as 100. Numbers smaller than 1 million are displayed as 0. Two adjacent thousand separators in any position other than immediately to the left of the decimal separator are treated simply as specifying the use of a thousand separator. The actual character used as the thousand separator in the formatted output depends on the Number Format recognized by your system.
(:) Time separator. In some locales, other characters may be used to represent the time separator. The time separator separates hours, minutes, and seconds when time values are formatted. The actual character used as the time separator in formatted output is determined by your system settings.
(/) Date separator. In some locales, other characters may be used to represent the date separator. The date separator separates the day, month, and year when date values are formatted. The actual character used as the date separator in formatted output is determined by your system settings.
(E- E+ e- e+) Scientific format. If the format expression contains at least one digit placeholder (0 or #) to the right of E-, E+, e-, or e+, the number is displayed in scientific format and E or e is inserted between the number and its exponent. The number of digit placeholders to the right determines the number of digits in the exponent. Use E- or e- to place a minus sign next to negative exponents. Use E+ or e+ to place a minus sign next to negative exponents and a plus sign next to positive exponents.
— + $ ( ) Display a literal character. To display a character other than one of those listed, precede it with a backslash () or enclose it in double quotation marks (» «).
() Display the next character in the format string. To display a character that has special meaning as a literal character, precede it with a backslash (). The backslash itself isn’t displayed. Using a backslash is the same as enclosing the next character in double quotation marks. To display a backslash, use two backslashes (\). Examples of characters that can’t be displayed as literal characters are the date-formatting and time-formatting characters (a, c, d, h, m, n, p, q, s, t, w, y, /, and :), the numeric-formatting characters (#, 0, %, E, e, comma, and period), and the string-formatting characters (@, &, <, >, and !).
(«ABC») Display the string inside the double quotation marks (» «). To include a string in format from within code, you must use Chr(34) to enclose the text (34 is the character code for a quotation mark («)).

See also

  • Functions (Visual Basic for Applications)

[!includeSupport and feedback]

И так, в этой по своей природе унылой публикации я кратко рассмотрю vba функции даты и времени, которые позволяют получить или установить параметры даты и времени, задать таймер выполнения заданного блока кода или сценария в целом. Также в конце статьи будет затронута функция vba языка format. Которая отвечает за форматирование данных.

Функции VBA даты и времени

Date() – позволяет получить значение текущей даты, установленной в системе.

Time() – вернет установленное в системе время

Now() – комбинированная функция, так как она позволяет получить значение системной даты и времени.

DateAdd(интервал, число, дата) – позволяет прибавить к заданной дате (параметр “дата”) указанное количество лет, кварталов, месяцев или секунд. На выходе мы получим следующее значение: дата + (число * интервал).

DateDiff(интервал, дата, дата2) – позволяет получить разницу между заданными датами, например. В годах, месяцах и так далее, разница определяется параметром “интервал”.

DatePart(интервал, дата) – позволяет получить заданную часть даты, например, только значение года, месяца или дня недели. Результат возврата регулируется параметром “интервал”.

DateSerial(год, месяц, день) – данная функция vba принимает три числовые значения, по которым возвращается дата.

DateValue(строка) – аналог предыдущей функции, но тут в качестве параметра мы передаем не числа. А строковое значение, на основе которого будет возвращаться дата, vba работа с датами.

Day(дата) – позволяет получить значение текущего дня (если отсутствует параметр “дата”) или для заданной даты.

Year(дата) – позволяет получить значение текущего года (если отсутствует параметр “дата”) или для заданной даты.

Month(дата) – позволяет получить значение текущего месяца (если отсутствует параметр “дата”) или для заданной даты.

Weekday(дата) – позволяет получить значение текущей недели (если отсутствует параметр “дата”) или для заданной даты.

Hour(время) – позволяет получить текущее значение часов (если отсутствует параметр “время”) или для заданного времени, vba дата и время.

Minute(время) – позволяет получить текущее значение минут (если отсутствует параметр “время”) или для заданного времени.

Second(время) – позволяет получить текущее значение секунд (если отсутствует параметр “время”) или для заданного времени.

Timer() – удобная функция для определения промежутка времени, ушедшего на выполнение заданного блока кода. Сама функция возвращает целое количество секунд, которые прошли начиная с полуночи.

TimeSerial(часы, минуты, секунды) – позволяет получить время, заданное тремя параметрами

TimeValue(строка) – работает аналогично предыдущей функции, но для получения времени, передается не целое значение, а строковое.

MonthName(числовое значение) – VBA функция позволяет получить название месяца, в качестве параметра указываем номер месяца.

WeekDay(дата) — задает возвращает имя месяца словами по его номеру. Возвращаемое значение зависит от региональных настроек. Если они русские, то вернется русское название месяца.

Помимо указанных выше vba функций даты и времени, можно использовать и такие вариации:

Date (дата) – позволяет задать системную дату

Time (время) – позволяет задать системное время.

В приведенных выше функциях даты и времени vba языка используется параметр “интервал”, который может принимать следующие значения:

  • w – недели
  • q – квартал
  • d – месяца
  • y – года

VBA функции форматирование данных

Для форматирования данных в языке VBA используется функция Format, которая позволяет сформировать данные любого встроенного типа, используя заданный образец. Общий синтаксис функции format:

Format(Выражение, [“формат”, [первый день недели, [первая неделя года]]]) – тут параметр “выражение” является любым допустимым значением. Формат – необязательный параметр, который задает формат данных, должен заключаться в кавычки. Остальные два параметра также являются необязательными, и задают день недели, который нужно считать первым, и первую неделю года.

Параметр формат может принимать следующие значения:

  • General Number – числовое значение без выделения разрядов тысяч, например, 12150,2003
  • Currency – денежный формат, выделяются тысячные разряды и два знака после запятой, например, 255,33р.
  • Fixed – числовое значение без выделения разрядов тысяч и двумя знаками после запятой, например, 22439,12.
  • Standart – числовое значение, которое умножается на 100, при этом, остаются два знака после запятой и символ процента, например, 55,63%.
  • Scientific – числовой формат для научных вычисление, например, 5,23Е+03
  • Yes/No – данный параметр определяет, что функция вернет “Да” если форматированное выражение содержит строку Нет, или ненулевое значение и “Нет” в противном случае.
  • True/False – аналог предыдущего параметра, но для строк “Истина” и “Ложь”.
  • On/Off – для строк вида “Вкл” и “Выкл”.
  • General Date – форматирование выражения в соответствии с установленными в системе стандартами даты и времени, например, 10.11.02 12:25:50
  • Long Date – вывод полного формата даты, в зависимости от установок в системе, например, 10 октября 2013 г, vba функции даты.
  • Medium Date – средний формат дат, например, 10-Окт-13.
  • Short Date – короткий вывод формата даты, например, 10.10.13.
  • Long Time – вывод в формате времени (часы, минуты, секунды), например, 12:20:40.
  • Medium Time – 12 часовой формат времени (часы, минуты), например, 05:30.
  • Short Time — 24 часовой формат времени (часы, минуты), например, 17:30.

Функции даты и времени VBScript помогают разработчикам преобразовывать дату и время из одного формата в другой или выражать дату или время в формате, соответствующем определенному условию.

Содержание:

  • Date
  • CDate
  • DateAdd
  • DateDiff
  • DatePart
  • DateSerial
  • FormatDateTime
  • IsDate
  • Day
  • Month
  • Year
  • MonthName
  • WeekDay
  • Now
  • Hour
  • Minute
  • Second
  • Time
  • Timer
  • TimeSerial
  • TimeValue

Date

Функция возвращает текущую системную дату.

Синтаксис

date()

пример

Добавьте кнопку и добавьте следующую функцию.

Sub Constant_demo_Click()
   Dim a as Variant
   a = date()
   msgbox "The Value of a : " & a
End Sub

Когда вы выполняете функцию, она производит следующий вывод.

The Value of a : 19/07/2014

Функция, которая возвращает текущую системную дату.

CDate

Функция преобразует действительное выражение даты и времени для ввода даты.

Синтаксис

cdate(date)

пример

Добавьте кнопку и добавьте следующую функцию.

Sub Constant_demo_Click()
   Dim a As Variant
   Dim b As Variant
   
   a = CDate("Янв 01 2020")
   MsgBox ("The Value of a : " & a)
   
   b = CDate("31 Дек 2050")
   MsgBox ("The Value of b : " & b)
End Sub

Когда вы выполняете функцию, она производит следующий вывод.

The Value of a : 1/01/2020
The Value of b : 31/12/2050

Функция, которая преобразует данный вход в дату.

DateAdd

Функция, которая возвращает дату, к которой был добавлен указанный временной интервал.

Синтаксис

DateAdd(interval,number,date)

Параметр/Описание

  • Интервал — требуемый параметр. Он может принимать следующие значения.
  • d — день года
  • м — месяц года
  • y — год года
  • yyyy — year
  • w — день недели
  • ww — неделя
  • q — квартал
  • час — час
  • м — минута
  • s — секунда
  • Номер — требуемый параметр. Он может принимать как положительные, так и отрицательные параметры.
  • Дата — требуемый параметр. Вариант или литерал, представляющий дату добавления интервала.

пример

Sub Constant_demo_Click()
   ' Positive Interal
   date1 = 1 - Jan - 2013
   MsgBox ("Line 1 : " & DateAdd("yyyy", 1, date1))
   MsgBox ("Line 2 : " & DateAdd("q", 1, date1))
   MsgBox ("Line 3 : " & DateAdd("m", 1, date1))
   MsgBox ("Line 4 : " & DateAdd("y", 1, date1))
   MsgBox ("Line 5 : " & DateAdd("d", 1, date1))
   MsgBox ("Line 6 : " & DateAdd("w", 1, date1))
   MsgBox ("Line 7 : " & DateAdd("ww", 1, date1))
   MsgBox ("Line 8 : " & DateAdd("h", 1, "01-Янв-2013 12:00:00"))
   MsgBox ("Line 9 : " & DateAdd("n", 1, "01-Янв-2013 12:00:00"))
   MsgBox ("Line 10 : " & DateAdd("s", 1, "01-Янв-2013 12:00:00"))
  
   ' Negative Interval
   MsgBox ("Line 11 : " & DateAdd("yyyy", -1, date1))
   MsgBox ("Line 12 : " & DateAdd("q", -1, date1))
   MsgBox ("Line 13 : " & DateAdd("m", -1, date1))
   MsgBox ("Line 14 : " & DateAdd("y", -1, date1))
   MsgBox ("Line 15 : " & DateAdd("d", -1, date1))
   MsgBox ("Line 16 : " & DateAdd("w", -1, date1))
   MsgBox ("Line 17 : " & DateAdd("ww", -1, date1))
   MsgBox ("Line 18 : " & DateAdd("h", -1, "01-Янв-2013 12:00:00"))
   MsgBox ("Line 19 : " & DateAdd("n", -1, "01-Янв-2013 12:00:00"))
   MsgBox ("Line 20 : " & DateAdd("s", -1, "01-Янв-2013 12:00:00"))
End Sub

Когда вы выполняете вышеуказанную функцию, она производит следующий вывод.

Line 1 : 27/06/1895
Line 2 : 27/09/1894
Line 3 : 27/07/1894
Line 4 : 28/06/1894
Line 5 : 28/06/1894
Line 6 : 28/06/1894
Line 7 : 4/07/1894
Line 8 : 1/01/2013 1:00:00 PM
Line 9 : 1/01/2013 12:01:00 PM
Line 10 : 1/01/2013 12:00:01 PM
Line 11 : 27/06/1893
Line 12 : 27/03/1894
Line 13 : 27/05/1894
Line 14 : 26/06/1894
Line 15 : 26/06/1894
Line 16 : 26/06/1894
Line 17 : 20/06/1894
Line 18 : 1/01/2013 11:00:00 AM
Line 19 : 1/01/2013 11:59:00 AM
Line 20 : 1/01/2013 11:59:59 AM

Функция, которая возвращает дату, к которой был добавлен указанный временной интервал.

DateDiff

Функция, которая возвращает разницу между двумя заданными временными интервалами.

Синтаксис

DateDiff(interval, date1, date2 [,firstdayofweek[, firstweekofyear]])

Параметр/Описание

  • Интервал — требуемый параметр. Он может принимать следующие значения.
  • d — день года
  • м — месяц года
  • y — год года
  • yyyy — year
  • w — день недели
  • ww — неделя
  • q — квартал
  • час — час
  • м — минута
  • s — секунда
  • Date1 и Date2 — Необходимые параметры.
  • Firstdayofweek — необязательный параметр. Задает первый день недели. Он может принимать следующие значения.
  • 0 = vbUseSystemDayOfWeek — настройка API поддержки национальных языков (NLS)
  • 1 = vbSunday — воскресенье
  • 2 = vbMonday — понедельник
  • 3 = vbTuesday — вторник
  • 4 = vbWednesday — среда
  • 5 = vbThursday — четверг
  • 6 = vbFriday — пятница
  • 7 = vbSaturday — суббота
  • Firstdayofyear — необязательный параметр. Указывает на первый день года. Он может принимать следующие значения.
  • 0 = vbUseSystem — настройка API поддержки национальных языков (NLS)
  • 1 = vbFirstJan1 — начать с недели, в которой происходит 1 января (по умолчанию)
  • 2 = vbFirstFourDays — Начните с недели, которая имеет не менее четырех дней в новом году
  • 3 = vbFirstFullWeek — начните с первой полной недели нового года

пример

Добавьте кнопку и добавьте следующую функцию.

Sub Constant_demo_Click()
   Dim fromDate As Variant
   fromDate = "01-Янв-09 00:00:00"
   
   Dim toDate As Variant
   toDate = "01-Янв-10 23:59:00"
   
   MsgBox ("Line 1 : " & DateDiff("yyyy", fromDate, toDate))
   MsgBox ("Line 2 : " & DateDiff("q", fromDate, toDate))
   MsgBox ("Line 3 : " & DateDiff("m", fromDate, toDate))
   MsgBox ("Line 4 : " & DateDiff("y", fromDate, toDate))
   MsgBox ("Line 5 : " & DateDiff("d", fromDate, toDate))
   MsgBox ("Line 6 : " & DateDiff("w", fromDate, toDate))
   MsgBox ("Line 7 : " & DateDiff("ww", fromDate, toDate))
   MsgBox ("Line 8 : " & DateDiff("h", fromDate, toDate))
   MsgBox ("Line 9 : " & DateDiff("n", fromDate, toDate))
   MsgBox ("Line 10 : " & DateDiff("s", fromDate, toDate))
End Sub

Когда вы выполняете вышеуказанную функцию, она производит следующий вывод.

Line 1 : 1
Line 2 : 4
Line 3 : 12
Line 4 : 365
Line 5 : 365
Line 6 : 52
Line 7 : 52
Line 8 : 8783
Line 9 : 527039
Line 10 : 31622340

Функция, которая возвращает разницу между двумя периодами времени.

DatePart

Функция, возвращающая определенную часть данной даты.

Синтаксис

DatePart(interval,date[,firstdayofweek[,firstweekofyear]])

Параметр/Описание

  • Интервал — требуемый параметр. Он может принимать следующие значения.
  • d — день года
  • м — месяц года
  • y — год года
  • yyyy — year
  • w — день недели
  • ww — неделя
  • q — квартал
  • час — час
  • м — минута
  • s — секунда
  • Date1 — обязательный параметр.
  • Firstdayofweek — необязательный параметр. Задает первый день недели. Он может принимать следующие значения.
  • 0 = vbUseSystemDayOfWeek — настройка API поддержки национальных языков (NLS)
  • 1 = vbSunday — воскресенье
  • 2 = vbMonday — понедельник
  • 3 = vbTuesday — вторник
  • 4 = vbWednesday — среда
  • 5 = vbThursday — четверг
  • 6 = vbFriday — пятница
  • 7 = vbSaturday — суббота
  • Firstdayofyear — необязательный параметр. Указывает на первый день года. Он может принимать следующие значения.
  • 0 = vbUseSystem — настройка API поддержки национальных языков (NLS)
  • 1 = vbFirstJan1 — начать с недели, в которой происходит 1 января (по умолчанию)
  • 2 = vbFirstFourDays — Начните с недели, которая имеет не менее четырех дней в новом году
  • 3 = vbFirstFullWeek — начните с первой полной недели нового года

пример

Добавьте кнопку и добавьте следующую функцию.

Sub Constant_demo_Click()
   Dim Quarter As Variant
   Dim DayOfYear As Variant
   Dim WeekOfYear As Variant
  
   Date1 = "2013-01-15"
   Quarter = DatePart("q", Date1)
   
   MsgBox ("Line 1 : " & Quarter)
   DayOfYear = DatePart("y", Date1)
   
   MsgBox ("Line 2 : " & DayOfYear)
   WeekOfYear = DatePart("ww", Date1)
   
   MsgBox ("Line 3 : " & WeekOfYear)
   MsgBox ("Line 4 : " & DatePart("m", Date1))
End Sub

Когда вы выполняете вышеуказанную функцию, она производит следующий вывод.

Line 1 : 1
Line 2 : 15
Line 3 : 3
Line 4 : 1

Функция, возвращающая указанную часть заданного значения даты ввода.

DateSerial

Функция, которая возвращает дату для заданных параметров дня, месяца и года.

Синтаксис

DateSerial(year,month,day)

Параметр/Описание

  • Год — требуемый параметр. Число от 100 до 9999 или числовое выражение. Значения от 0 до 99 интерпретируются как годы с 1900 по 1999 год. Для всех аргументов за другой год используйте полный четырехзначный год.
  • Месяц — требуемый параметр. Он также может быть в форме выражения, которое должно варьироваться от 1 до 12.
  • День — требуемый параметр. Он также может быть в форме выражения, которое должно варьироваться от 1 до 31.

пример

Добавьте кнопку и добавьте следующую функцию.

Sub Constant_demo_Click()
   msgbox(DateSerial(2013,5,10))
End Sub

Когда вы выполняете вышеуказанную функцию, она производит следующий вывод.

10/05/2013

Функция, которая возвращает действительную дату для данного года, месяца и даты.

FormatDateTime

Функция, которая помогает разработчикам форматировать и возвращать действительное выражение даты и времени.

Синтаксис

FormatDateTime(date,format)

Параметр/Описание

  • Дата — требуемый параметр.
  • Формат — необязательный параметр. Значение, определяющее формат даты или времени, который будет использоваться. Он может принимать следующие значения.
  • 0 = vbGeneralDate — Default
  • 1 = vbLongDate — дата возврата
  • 2 = vbShortDate — Дата возврата
  • 3 = vbLongTime — возвращает время
  • 4 = vbShortTime — возвращает время

пример

Добавьте кнопку и добавьте следующую функцию.

Sub Constant_demo_Click()
   d = ("2013-08-15 20:25")
   msgbox("Line 1 : " & FormatDateTime(d))
   msgbox("Line 2 : " & FormatDateTime(d,1))
   msgbox("Line 3 : " & FormatDateTime(d,2))
   msgbox("Line 4 : " & FormatDateTime(d,3))
   msgbox("Line 5 : " & FormatDateTime(d,4))
End Sub

Когда вы выполняете вышеуказанную функцию, она производит следующий вывод.

Line 1 : 15/08/2013 8:25:00 PM
Line 2 : Thursday, 15 August 2013
Line 3 : 15/08/2013
Line 4 : 8:25:00 PM
Line 5 : 20:25

Функция, которая форматирует дату на основе поставляемых параметров.

IsDate

Функция, возвращающая логическое значение, независимо от того, является ли данный ввод датой.

Синтаксис

IsDate(expression)

пример

Добавьте кнопку и добавьте следующую функцию.

Sub Constant_demo_Click()
   msgbox("Line 1 : " & IsDate("Nov 03, 1950"))
   msgbox("Line 2 : " & IsDate(#01/31/20#))
   msgbox("Line 3 : " & IsDate(#05/31/20 10:30 PM#))
End Sub

Когда вы выполняете вышеуказанную функцию, она производит следующий вывод.

Line 1 : True
Line 2 : True
Line 3 : True

Функция, возвращающая логическое значение, независимо от того, является ли поставленный параметр датой.

Day

Функция «День» возвращает число от 1 до 31, которое представляет день указанной даты.

Синтаксис

Day(date)

пример

Добавьте кнопку и добавьте следующую функцию.

Sub Constant_demo_Click()
   msgbox(Day("2013-06-30"))
End Sub

Когда вы выполняете вышеуказанную функцию, она производит следующий вывод.

30

Функция, которая возвращает целое число от 1 до 31, которое представляет день указанной даты.

Month

Функция Month возвращает число от 1 до 12, которое представляет месяц указанной даты.

Синтаксис

Month(date)

пример

Добавьте кнопку и добавьте следующую функцию.

Sub Constant_demo_Click()
   msgbox(Month("2013-06-30"))
End Sub

Когда вы выполняете вышеуказанную функцию, она производит следующий вывод.

6

Функция, которая возвращает целое число от 1 до 12, которое представляет месяц указанной даты.

Year

Функция Год возвращает целое число, которое представляет год указанной даты.

Синтаксис

Year(date)

пример

Добавьте кнопку и добавьте следующую функцию.

Sub Constant_demo_Click()
   msgbox(Year("2013-06-30"))
End sub

Когда вы выполняете вышеуказанную функцию, она производит следующий вывод.

2013

Функция, которая возвращает целое число, которое представляет год указанной даты.

MonthName

Функция MonthName возвращает имя месяца для указанной даты.

Синтаксис

MonthName(month[,toabbreviate])

Параметр Описание

  • Месяц — требуемый параметр. Он определяет номер месяца.
  • Toabbreviate — необязательный параметр. Булевское значение, указывающее, следует ли сокращать имя месяца. Если оставить пустым, значение по умолчанию будет считаться False.

пример

Добавьте кнопку и добавьте следующую функцию.

Sub Constant_demo_Click()
   msgbox("Line 1 : " & MonthName(01,True))
   msgbox("Line 2 : " & MonthName(01,false))
   msgbox("Line 3 : " & MonthName(07,True))
   msgbox("Line 4 : " & MonthName(07,false))
End Sub

Когда вы выполняете вышеуказанную функцию, она производит следующий вывод.

Line 1 : Jan
Line 2 : January
Line 3 : Jul
Line 4 : July

Функция, которая возвращает имя определенного месяца за указанную дату.

WeekDay

Функция WeekDay возвращает целое число от 1 до 7, которое представляет день недели для указанной даты.

Синтаксис

Weekday(date[,firstdayofweek])

Параметр/Описание

    Дата — требуемый параметр. День недели вернет указанную дату. Firstdayofweek — необязательный параметр. Задает первый день недели. Он может принимать следующие значения. 0 = vbUseSystemDayOfWeek — настройка API поддержки национальных языков (NLS) 1 = vbSunday — воскресенье 2 = vbMonday — понедельник 3 = vbВперед — вторник 4 = vbWednesday — среда 5 = vbThursday — четверг 6 = vbFriday — пятница 7 = vbSaturday — суббота

пример

Добавьте кнопку и добавьте следующую функцию.

Sub Constant_demo_Click()
   msgbox("Line 1: " & Weekday("2013-05-16",1))
   msgbox("Line 2: " & Weekday("2013-05-16",2))
   msgbox("Line 3: " & Weekday("2013-05-16",2))
   msgbox("Line 4: " & Weekday("2010-02-16"))
   msgbox("Line 5: " & Weekday("2010-02-17"))
   msgbox("Line 6: " & Weekday("2010-02-18"))
End Sub

Когда вы выполняете вышеуказанную функцию, она производит следующий вывод.

Line 1: 5
Line 2: 4
Line 3: 4
Line 4: 3
Line 5: 4
Line 6: 5

Функция, которая возвращает целое число (от 1 до 7), которое представляет день недели в течение указанного дня.

WeekDayName

Функция WeekDayName возвращает имя дня недели за указанный день.

Синтаксис WeekdayName(weekday[,abbreviate[,firstdayofweek]])

Параметр — Описание

  • Weekday — требуемый параметр. Номер дня недели.
  • Toabbreviate — необязательный параметр. Булевское значение, указывающее, следует ли сокращать имя месяца. Если оставить пустым, значение по умолчанию будет считаться False.
  • Firstdayofweek — необязательный параметр. Задает первый день недели.
  • 0 = vbUseSystemDayOfWeek — настройка API поддержки национальных языков (NLS)
  • 1 = vbSunday — воскресенье
  • 2 = vbMonday — понедельник
  • 3 = vbTuesday — вторник
  • 4 = vbWednesday — среда
  • 5 = vbThursday — четверг
  • 6 = vbFriday — пятница
  • 7 = vbSaturday — суббота

пример

Добавьте кнопку и добавьте следующую функцию.

Sub Constant_demo_Click()
   msgbox("Line 1 : " & WeekdayName(3))
   msgbox("Line 2 : " & WeekdayName(2,True))
   msgbox("Line 3 : " & WeekdayName(1,False))
   msgbox("Line 4 : " & WeekdayName(2,True,0))
   msgbox("Line 5 : " & WeekdayName(1,False,1))
End Sub

Когда вы выполняете вышеуказанную функцию, она производит следующий вывод.

Line 1 : Tuesday
Line 2 : Mon
Line 3 : Sunday
Line 4 : Tue
Line 5 : Sunday

Функция, которая возвращает имя дня недели для указанного дня.

Now

Функция Now возвращает текущую системную дату и время.

Синтаксис

Now()

пример

Добавьте кнопку и добавьте следующую функцию.

Sub Constant_demo_Click()
   Dim a as Variant
   a = Now()
   msgbox("The Value of a : " & a)
End Sub

Когда вы выполняете вышеуказанную функцию, она производит следующий вывод. The Value of a : 19/07/2013 3:04:09 PM

Функция, которая возвращает текущую системную дату и время.

Hour

Функция Hour возвращает число от 0 до 23, которое представляет час дня для указанной отметки времени.

Синтаксис

Hour(time)

пример

Добавьте кнопку и добавьте следующую функцию.

Sub Constant_demo_Click()
   msgbox("Line 1: " & Hour("3:13:45 PM"))
   msgbox("Line 2: " & Hour("23:13:45"))
   msgbox("Line 3: " & Hour("2:20 PM"))
End Sub

Когда вы выполняете вышеуказанную функцию, она производит следующий вывод.

Line 1: 15
Line 2: 23
Line 3: 14

Функция, которая возвращает целое число от 0 до 23, которое представляет часовую часть заданного времени.

Minute

Функция Minute возвращает число от 0 до 59, которое представляет минуту часа для указанной отметки времени.

Синтаксис

Minute(time)

пример

Добавьте кнопку и добавьте следующую функцию.

Sub Constant_demo_Click()
   msgbox("Line 1: " & Minute("3:13:45 PM"))
   msgbox("Line 2: " & Minute("23:43:45"))
   msgbox("Line 3: " & Minute("2:20 PM"))
End Sub

Когда вы выполняете вышеуказанную функцию, она производит следующий вывод.

Line 1: 13
Line 2: 43
Line 3: 20

Функция, возвращающая целое число от 0 до 59, которое представляет минутную часть данного времени.

Second

Функция возвращает число от 0 до 59, которое представляет вторую часть часа для указанной отметки времени.

Синтаксис

Second(time)

пример

Добавьте кнопку и добавьте следующую функцию.

Sub Constant_demo_Click()
   msgbox("Line 1: " & Second("3:13:25 PM"))
   msgbox("Line 2: " & Second("23:13:45"))
   msgbox("Line 3: " & Second("2:20 PM"))
End Sub

Когда вы выполняете вышеуказанную функцию, она производит следующий вывод. Line 1: 25
Line 2: 45
Line 3: 0

Функция, возвращающая целое число от 0 до 59, которое представляет собой секундную часть данного времени.

Time

Функция времени возвращает текущее системное время.

Синтаксис

Time()

пример

Sub Constant_demo_Click()
   msgbox("Line 1: " & Time())
End Sub

Когда вы выполняете вышеуказанную функцию, она производит следующий вывод.

Line 1: 3:29:15 PM

Функция, которая возвращает текущее системное время.

Timer

Функция таймера возвращает число секунд и миллисекунд с 12:00.

Синтаксис

Timer()

пример

Добавьте кнопку и добавьте следующую функцию.

Sub Constant_demo_Click()
   msgbox("Time is : " & Now())
   msgbox("Timer is: " & Timer())
End Sub

Когда вы выполняете вышеуказанную функцию, она производит следующий вывод.

Time is : 19/07/2013 3:45:53 PM
Timer is: 56753.4

Функция, которая возвращает число секунд и миллисекунд с 12:00.

TimeSerial

Функция TimeSerial возвращает время для указанных часов, минут и вторых значений.

Синтаксис

TimeSerial(hour,minute,second)

Параметр/Описание

  • Hour — обязательный параметр, который представляет собой целое число от 0 до 23 или любое числовое выражение.
  • Minute — обязательный параметр, который представляет собой целое число от 0 до 59 или любое числовое выражение.
  • Second — обязательный параметр, который представляет собой целое число от 0 до 59 или любое числовое выражение.

пример

Добавьте кнопку и добавьте следующую функцию.

Sub Constant_demo_Click()
   msgbox(TimeSerial(20,1,2))
   msgbox(TimeSerial(0,59,59))
   msgbox(TimeSerial(7*2,60/3,15+3))
End Sub

Когда вы выполняете вышеуказанную функцию, она производит следующий вывод.

8:01:02 PM
12:59:59 AM
2:20:18 PM

Функция, которая возвращает время для конкретного ввода часа, минуты и секунды.

TimeValue

Функция TimeValue преобразует заданную входную строку в допустимое время.

Синтаксис

TimeValue(StringTime)

пример

Добавьте кнопку и добавьте следующую функцию.

Sub Constant_demo_Click() 
   msgbox(TimeValue("20:30"))
   msgbox(TimeValue("5:15"))
   msgbox(TimeValue("2:30:58"))
End Sub

Когда вы выполняете вышеуказанную функцию, она производит следующий вывод.

8:30:00 PM
5:15:00 AM
2:30:58 AM

Функция, которая преобразует входную строку в формат времени.

 С уважением, авторы сайта Компьютерапия

Понравилась статья? Поделитесь ею с друзьями и напишите отзыв в комментариях!

Содержание

  • 1 aaaa — Displays the full, localized name of the day.
  • 2 AM/PM — Uses the 12-hour clock and displays AM or PM as appropriate.
  • 3 AMPM — Uses the 12-hour clock and displays the AM or PM string literal defined for the system.
  • 4 A/P — Uses the 12-hour clock and displays A or P as appropriate.
  • 5 c — Displays the date
  • 6 / Date separator (also locale-dependent).
  • 7 dddddd — Displays the complete date (day, month, and year) in the system»s long date format.
  • 8 ddddd — Displays the complete date (day, month, and year) in the system»s short date format.
  • 9 dddd — Displays the full name of the day.
  • 10 ddd — Displays the day as a three-letter abbreviation (Sun, Mon, Tue, Wed, Thu, Fri, Sat) with no period.
  • 11 dd — Displays the date with a leading zero for single-digit numbers (01 to 31).
  • 12 d — Displays the date (1 to 31) without a leading zero for single-digit numbers.
  • 13 For example, the following statement returns Saturday, April:
  • 14 Format(datDateTime, «dd mmm yy»)
  • 15 Format(datDateTime, «Long Date»)
  • 16 Format(datDateTime, «mm dddd hh:mm»)
  • 17 Format(datDateTime, «yyyy-mm-dd»)
  • 18 format(Now, «ddd»)
  • 19 format(Now, «dddd»)
  • 20 format(Now, «ddddd»)
  • 21 format(Now, «dddddd»)
  • 22 format(Now, «d-mmmm-yy»)
  • 23 format(Now, «d-mmm-yy»)
  • 24 Format(Now, «Hh:Nn:Ss AM/PM»)
  • 25 format(Now, «mmmm d, yyyy»)
  • 26 Format(Now, «ttttt»)
  • 27 Format the date type value
  • 28 Format time as mmmm_yyyy
  • 29 formatting the date and time with format function
  • 30 h — Displays a number from 0 to 23 giving the hour.
  • 31 Hh — Displays a number from 00 to 23 giving the two-digit hour.
  • 32 m — Displays an integer from 1 to 12 giving the number of the month without a leading zero on single-digit months.
  • 33 mm — Displays a number from 01 to 12 giving the two-digit number of the month. When used after h returns minutes instead of months.
  • 34 mmm — Displays the month as a three-letter abbreviation (except for May) without a period.
  • 35 mmmm — Displays the full name of the month.
  • 36 N — Displays a number from 0 to 60 giving the minute.
  • 37 Nn — Displays a number from 00 to 60 giving the two-digit minute.
  • 38 oooo — Displays the full localized name of the month.
  • 39 q — Displays a number from 1 to 4 giving the quarter of the year.
  • 40 S — Displays a number from 0 to 60 giving the second.
  • 41 Ss — Displays a number from 00 to 60 giving the two-digit second.
  • 42 : — Time separator (typically a colon, but this depends on the locale).
  • 43 ttttt — Displays the full time (hour, minute, and second) in the system»s default time format.
  • 44 Using the Format Function to Format an Expression: Format(expression[, format[, firstdayofweek[, firstweekofyear]]])
  • 45 w — Displays an integer from 1 (Sunday) to 7 (Monday) containing the day of the week.
  • 46 ww — Displays an integer from 1 to 54 giving the number of the week in the year.
  • 47 y — Displays an integer from 1 to 366 giving the day of the year.
  • 48 yy — Displays a number from 00 to 99 giving the two-digit year.
  • 49 yyyy — Displays a number from o iving the four-digit year.

aaaa — Displays the full, localized name of the day.

   <source lang="vb">

Sub formatDemo11()

   Debug.Print Format(#4/1/2006 12:36:54 PM#, "aaaa")

End Sub

</source>
   
  

AM/PM — Uses the 12-hour clock and displays AM or PM as appropriate.

   <source lang="vb">

Sub formatDemo30()

   Debug.Print Format(#4/1/2006 12:36:54 PM#, "AM")

End Sub

</source>
   
  

AMPM — Uses the 12-hour clock and displays the AM or PM string literal defined for the system.

   <source lang="vb">

Sub formatDemo34()

   Debug.Print Format(#4/1/2006 12:36:54 PM#, "AMPM")

End Sub

</source>
   
  

A/P — Uses the 12-hour clock and displays A or P as appropriate.

   <source lang="vb">

Sub formatDemo32()

   Debug.Print Format(#4/1/2006 12:36:54 PM#, "A")

End Sub

</source>
   
  

c — Displays the date

   <source lang="vb">

Sub formatDemo5()

   Debug.Print Format(#4/1/2006 12:36:54 PM#, "c")

End Sub

</source>
   
  

/ Date separator (also locale-dependent).

   <source lang="vb">

Sub formatDemo3()

   Debug.Print Format(#4/1/2006 12:36:54 PM#, "dddddd")

End Sub

</source>
   
  

dddddd — Displays the complete date (day, month, and year) in the system»s long date format.

   <source lang="vb">

Sub formatDemo10()

   Debug.Print Format(#4/1/2006 12:36:54 PM#, "dddddd")

End Sub

</source>
   
  

ddddd — Displays the complete date (day, month, and year) in the system»s short date format.

   <source lang="vb">

Sub formatDemo9()

   Debug.Print Format(#4/1/2006 12:36:54 PM#, "ddddd")

End Sub

</source>
   
  

dddd — Displays the full name of the day.

   <source lang="vb">

Sub formatDemo8()

   Debug.Print Format(#4/1/2006 12:36:54 PM#, "dddd")

End Sub

</source>
   
  

ddd — Displays the day as a three-letter abbreviation (Sun, Mon, Tue, Wed, Thu, Fri, Sat) with no period.

   <source lang="vb">

Sub formatDemo7()

   Debug.Print Format(#4/1/2006 12:36:54 PM#, "ddd")

End Sub

</source>
   
  

dd — Displays the date with a leading zero for single-digit numbers (01 to 31).

   <source lang="vb">

Sub formatDemo6()

   Debug.Print Format(#4/1/2006 12:36:54 PM#, "dd")

End Sub

</source>
   
  

d — Displays the date (1 to 31) without a leading zero for single-digit numbers.

   <source lang="vb">

Sub formatDemo4()

   Debug.Print Format(#4/1/2006 12:36:54 PM#, "d")

End Sub

</source>
   
  

For example, the following statement returns Saturday, April:

   <source lang="vb">

Sub formatDemo35()

   Debug.Print Format(#4/1/2006 12:36:54 PM#, "dddddd")

End

</source>
   
  

Format(datDateTime, «dd mmm yy»)

   <source lang="vb">

Sub dateFormat2()

   Dim datDateTime As Date
   datDateTime = #11/30/1998 10:54:17 AM#
   Debug.Print datDateTime
   Debug.Print format(datDateTime, "dd mmm yy")

End Sub

</source>
   
  

Format(datDateTime, «Long Date»)

   <source lang="vb">

Sub dateFormat1()

   Dim datDateTime As Date
   datDateTime = #11/30/1998 10:54:17 AM#
   Debug.Print datDateTime
   Debug.Print format(datDateTime, "Long Date")

End Sub

</source>
   
  

Format(datDateTime, «mm dddd hh:mm»)

   <source lang="vb">

Sub dateFormat()

   Dim datDateTime As Date
   datDateTime = #11/30/1998 10:54:17#
   Debug.Print datDateTime
   Debug.Print Format(datDateTime, "mm dddd hh:mm")      

End Sub

</source>
   
  

Format(datDateTime, «yyyy-mm-dd»)

   <source lang="vb">

Sub dateFormat3()

   Dim datDateTime As Date
   datDateTime = #11/30/1998 10:54:17 AM#
   Debug.Print datDateTime
   Debug.Print format(datDateTime, "yyyy-mm-dd")

End Sub

</source>
   
  

format(Now, «ddd»)

   <source lang="vb">

Sub dateFunctions6()

   Debug.Print "ddd: " & format(Now, "ddd")

End Sub

</source>
   
  

format(Now, «dddd»)

   <source lang="vb">

Sub dateFunctions7()

   Debug.Print "dddd: " & format(Now, "dddd")

End Sub

</source>
   
  

format(Now, «ddddd»)

   <source lang="vb">

Sub dateFunctions8()

   Debug.Print "ddddd: " & format(Now, "ddddd")

End Sub

</source>
   
  

format(Now, «dddddd»)

   <source lang="vb">

Sub dateFunctions9()

   Debug.Print "dddddd: " & format(Now, "dddddd")

End Sub

</source>
   
  

format(Now, «d-mmmm-yy»)

   <source lang="vb">

Sub dateFunctions4()

   Debug.Print "d-mmmm-yy: " & format(Now, "d-mmmm-yy")

End Sub

</source>
   
  

format(Now, «d-mmm-yy»)

   <source lang="vb">

Sub dateFunctions3()

   Debug.Print "d-mmm-yy: " & format(Now, "d-mmm-yy")

End Sub

</source>
   
  

Format(Now, «Hh:Nn:Ss AM/PM»)

   <source lang="vb">

Sub dateFunctions()

   Debug.Print "Hh:Nn:Ss AM/PM: " & Format(Now, "Hh:Nn:Ss AM/PM")

End Sub

</source>
   
  

format(Now, «mmmm d, yyyy»)

   <source lang="vb">

Sub dateFunctions5()

   Debug.Print "mmmm d, yyyy: " & format(Now, "mmmm d, yyyy")

End Sub

</source>
   
  

Format(Now, «ttttt»)

   <source lang="vb">

Sub dateFunctions()

   Debug.Print "ttttt: " & Format(Now, "ttttt")

End Sub

</source>
   
  

Format the date type value

   <source lang="vb">

Sub FindDates()

   On Error GoTo errorHandler
   Dim startDate As String
   Dim stopDate As String
   startDate = Format("12/12/1900", "mm/??/yy")
   stopDate = Format("12/12/2000", "mm/??/yy")
   MsgBox startDate
  
   End
   errorHandler:
   MsgBox "There has been an error:  " & Error() & Chr(13) _
       & "Ending Sub.......Please try again", 48

End Sub

</source>
   
  

Format time as mmmm_yyyy

   <source lang="vb">

Sub FormatNow()

   Dim myWorksheetName As String
   myWorksheetName = Format(Now, "mmmm_yyyy")
   MsgBox myWorksheetName

End Sub

</source>
   
  

formatting the date and time with format function

   <source lang="vb">

Sub dateFunctions()

  Dim strDateString As String
  strDateString = "m/d/yy: " & Format(Now, "m/d/yy") & vbCrLf & _
                  "d-mmm-yy: " & Format(Now, "d-mmm-yy") & vbCrLf & _
                  "d-mmmm-yy: " & Format(Now, "d-mmmm-yy") & vbCrLf & _
                  "mmmm d, yyyy: " & Format(Now, "mmmm d, yyyy") & vbCrLf & _
                  "ddd: " & Format(Now, "ddd") & vbCrLf & _
                  "dddd: " & Format(Now, "dddd") & vbCrLf & _
                  "ddddd: " & Format(Now, "ddddd") & vbCrLf & _
                  "dddddd: " & Format(Now, "dddddd") & vbCrLf & _
                  "Hh:Nn:Ss AM/PM: " & Format(Now, "Hh:Nn:Ss AM/PM") & vbCrLf & _
                  "ttttt: " & Format(Now, "ttttt") & vbCrLf & _
                  "vbShortDate: " & FormatDateTime(Now, vbShortDate) & vbCrLf & _
                  "vbLongDate: " & FormatDateTime(Now, vbLongDate) & vbCrLf & _
                  "vbGeneralDate: " & FormatDateTime(Now, vbGeneralDate)
  msgBox strDateString

End Sub

</source>
   
  

h — Displays a number from 0 to 23 giving the hour.

   <source lang="vb">

Sub formatDemo23()

   Debug.Print Format(#4/1/2006 12:36:54 PM#, "h")

End Sub

</source>
   
  

Hh — Displays a number from 00 to 23 giving the two-digit hour.

   <source lang="vb">

Sub formatDemo24()

   Debug.Print Format(#4/1/2006 12:36:54 PM#, "Hh")
</source>
   
  

m — Displays an integer from 1 to 12 giving the number of the month without a leading zero on single-digit months.

   <source lang="vb">

Sub formatDemo14()

   Debug.Print Format(#4/1/2006 12:36:54 PM#, "m")

End Sub

</source>
   
  

mm — Displays a number from 01 to 12 giving the two-digit number of the month. When used after h returns minutes instead of months.

   <source lang="vb">

Sub formatDemo15()

   Debug.Print Format(#4/1/2006 12:36:54 PM#, "mm")

End Sub

</source>
   
  

mmm — Displays the month as a three-letter abbreviation (except for May) without a period.

   <source lang="vb">

Sub formatDemo16()

   Debug.Print Format(#4/1/2006 12:36:54 PM#, "mmm")

End Sub

</source>
   
  

mmmm — Displays the full name of the month.

   <source lang="vb">

Sub formatDemo17()

   Debug.Print Format(#4/1/2006 12:36:54 PM#, "mmmm")

End Sub

</source>
   
  

N — Displays a number from 0 to 60 giving the minute.

   <source lang="vb">

Sub formatDemo25()

   Debug.Print Format(#4/1/2006 12:36:54 PM#, "N")

End Sub

</source>
   
  

Nn — Displays a number from 00 to 60 giving the two-digit minute.

   <source lang="vb">

Sub formatDemo26()

   Debug.Print Format(#4/1/2006 12:36:54 PM#, "Nn")

End Sub

</source>
   
  

oooo — Displays the full localized name of the month.

   <source lang="vb">

Sub formatDemo18()

   Debug.Print Format(#4/1/2006 12:36:54 PM#, "oooo")

End Sub

</source>
   
  

q — Displays a number from 1 to 4 giving the quarter of the year.

   <source lang="vb">

Sub formatDemo19()

   Debug.Print Format(#4/1/2006 12:36:54 PM#, "q")

End Sub

</source>
   
  

S — Displays a number from 0 to 60 giving the second.

   <source lang="vb">

Sub formatDemo27()

   Debug.Print Format(#4/1/2006 12:36:54 PM#, "S")

End Sub

</source>
   
  

Ss — Displays a number from 00 to 60 giving the two-digit second.

   <source lang="vb">

Sub formatDemo28()

   Debug.Print Format(#4/1/2006 12:36:54 PM#, "Ss")

End Sub

</source>
   
  

: — Time separator (typically a colon, but this depends on the locale).

   <source lang="vb">

Sub formatDemo2()

   Debug.Print Format(#4/1/2006 12:36:54 PM#, "dddddd")

End Sub

</source>
   
  

ttttt — Displays the full time (hour, minute, and second) in the system»s default time format.

   <source lang="vb">

Sub formatDemo29()

   Debug.Print Format(#4/1/2006 12:36:54 PM#, "tttt")

End Sub

</source>
   
  

Using the Format Function to Format an Expression: Format(expression[, format[, firstdayofweek[, firstweekofyear]]])

   <source lang="vb">


Constant Value Year Starts with Week
vbUseSystem 0 Use the system setting.
vbFirstJan1 1 The week in which January 1 falls (the default setting).
vbFirstFourDays 2 The first week with a minimum of four days in the year.
vbFirstFullWeek 3 The first full week (7 days) of the year.

</source>
   
  

w — Displays an integer from 1 (Sunday) to 7 (Monday) containing the day of the week.

   <source lang="vb">

Sub formatDemo12()

   Debug.Print Format(#4/1/2006 12:36:54 PM#, "w")

End Sub

</source>
   
  

ww — Displays an integer from 1 to 54 giving the number of the week in the year.

   <source lang="vb">

Sub formatDemo13()

   Debug.Print Format(#4/1/2006 12:36:54 PM#, "ww")

End Sub

</source>
   
  

y — Displays an integer from 1 to 366 giving the day of the year.

   <source lang="vb">

Sub formatDemo20()

   Debug.Print Format(#4/1/2006 12:36:54 PM#, "y")

End Sub

</source>
   
  

yy — Displays a number from 00 to 99 giving the two-digit year.

   <source lang="vb">

Sub formatDemo21()

   Debug.Print Format(#4/1/2006 12:36:54 PM#, "yy")

End Sub

</source>
   
  

yyyy — Displays a number from o iving the four-digit year.

   <source lang="vb">

Sub formatDemo22()

   Debug.Print Format(#4/1/2006 12:36:54 PM#, "yyyy")

End Sub

</source>

Countdown Timer and Date, Calendar ScoreboardVBA stands for Visual Basic for Applications. It is different from Visual Basic. Microsoft came up with this programming feature to use with the Microsoft Office software suite. It can be used to create programs to be run on Microsoft Excel, Outlook or other components of the MS Office suite. In this intermediate level tutorial, we walk you through VBA Format function for date and time. VBA Format function takes an expression, a date or number value and converts the same into a string. We assume that you know the basic concepts of MS Excel and Visual Basic for Applications. You can learn more about VBA in this excellent course, or of you’re in a hurry, you can take this 24hr VBA trainer course.

How to Assign VBA Date Value to a Variable

You can set the format in any version of Microsoft Excel starting from Excel 2000 to Excel version 2013. You can assign any date format as a value to a variable with the date data type in Excel VBA. However, ensure that values are put between simple hash (#) tags. Here VBA converts the value to a “Date” that can be used in comparisons and other types of statements. The following examples show this:

D1 = #March 24, 2014#
D1 = #3/24/2014#
D1 = #03/24/2014#

VBA will interpret the above statements to the date “March 24, 2014.” Before we move on, to learn more about how you can use VBA with MS Excel, you may want to try out this primer course; or just crash through our VBA tutorial to brush up your understanding.

VBA Format Function

Microsoft Excel Format function accepts the date expression and returns it as a formatted string. The syntax of Format date function looks like this

Format (expression, [format, [firstdayofweek, [firstweekofyear] ] ] )

Let’s take a closer look at the parameters.

  1. Expression stands for the value to be formatted.
  2. Format stands for the format to be applied to the expression. It is optional. In VBA Format Date function you have the option to either define your own format or use some of the MS Excel predefined format.
  3. Firstdayofweek specifies the first day of the week. If it is not declared, the Format function assumes that Sunday is the first day of the week. This parameter is optional.
  4. Firstweekofyear is the value that specifies the first week of the year. However, if this parameter is not declared, then the Format function assumes that the first week begins from January 1.

The table given below displays some of the Excel predefined date format.

Format

Explanation
General Date Displays date depending  upon the system settings
Long Date Displays date  depending upon the system’s long date setting
Medium Date Displays date depending upon the system’s medium date setting
Short Date Displays date depending upon the system’s short date setting
Long Time Displays time depending upon the system’s long time setting
Medium Time Displays time depending upon the system’s medium time setting
Short Time Displays time depending upon the system’s short time setting

The table given below contains the values the parameter “firstdayoftheweek” can take up in your VBA programs.

Constant

Value

Explanation
vbUseSystem 0 Uses the NLS API (National Language Support  Application Program Interface) setting
VbSunday 1 Sunday (default, if parameter is not declared)
vbMonday 2 Monday
vbTuesday 3 Tuesday
vbWednesday 4 Wednesday
vbThursday 5 Thursday
vbFriday 6 Friday
vbSaturday 7 Saturday

The table below lists the possible values of the optional parameter “Firstweekofyear that you can use in your VBA programs. Take a look

Constant Value Explanation
vbUseSystem 0 Uses the NLS API setting
vbFirstJan1 1 The week that contains January 1
vbFirstFourDays 2 The first week that has at least 4 days in the year
vbFirstFullWeek 3 The first full week of the year

Here are a few examples of Format function for Date in Excel VBA to make this function more clear.

1. Format(#24/03/2014#, “Short Date”)    would return ’24/03/2014′

2. Format(#24/03/2014#, “Long Date”)     would return ‘March 24, 2014’

3. Format(#24/03/2014#, “yyyy/mm/dd”)    would return ‘2014/03/24’

We suggest that you work out more examples of your own on  date function format. That’ll help you get more comfortable with the various options.  This course with Mr Excel can help you get a good workout with Excel VBA examples.

User Defined Format Function for date and time

Note that you can also use some pre-defined variants of the Format function for date and time.  The syntax of that looks like this

Format (expression, style)

The table below shows the user-defined Format function for date and time. Read through carefully

Format Explanation
Format (Now, “M”) Displays the current month and date
Format (Now, “MM”) Displays the current month in double digits.
Format (Now, “MMM”) Displays  the abbreviated name of the current month
Format (Now, “MMMM”) Displays the full name of the current month.
Format (Now, “dd/MM/yyyy”) Displays the current date in the day/month/year format.
Format (Now, “MMM,d,yyyy”) Displays the current date in the Month, Day, Year Format
Format (Now, “h:mm:ss tt”) Displays the current time  in the format hour:minute:second and show am/pm
Format (Now, “MM/dd/yyyy  h:mm:ss) Displays current date and time  in the format hour:minute:second

Let’s take a closer look at the user-defined format function for date and time using a simple VBA program.

Sub Newbutton_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click, Button2.Click, Button3.Click
Label1.Text = Format(Now, "M")
Label2.Text = Format(Now, "MM")
Label3.Text = Format(Now, "MMM")
Label4.Text = Format(Now, "MMMM")
Label5.Text = Format(Now, "dd/MM/yyyy")
Label6.Text = Format(Now, "MMM,d,yyyy")
Label7.Text = Format(Now, "h:mm:ss tt")
Label8.Text = Format(Now, "MM/dd/yyyy h:mm:ss tt")
End Sub

When you run this program, it will display the current system date in different formats.

Label1.Text will display March 24
Label2.Text will display 03
Label3.Text will display Mar
Label4.Text will display March
Label5.Text will display 24/03/2014
Label6.Text will display Mar,24,2014
Label7.Text will display 12:49:23 PM
Label8.Text will display 03/24/2014 12:49:23 PM

Characters supported by VBA Date Function

VBA Date functions supports these characters to display date and time. It’s quite a long list, so check out the table below!

Characters Example Description
m 8 Month (numerical without zeros)
mm 08 Month (numerical with zeros)
mmm Sep Month (abbreviated text)
mmmm September Month (full-length text)
d 6 Day (numerical without zeros)
dd 06 Day (numerical with zeros)
ddd Wed Day (abbreviated text)
dddd Wednesday Days (full-length text)
yy 14 Year (last 2 digits)
yyyy 2014 Year (4 digits)
h 9 Hours without zeros (0-23)
hh 09 Hours with zeros (00-23)
n 7 Minutes without zeros (0-59)
nn 07 Minutes with zeros (00-59)
s 5 Seconds without zeros (0-59)
ss 05 Seconds with zeros (00-59)
AM/PM AM Display AM/PM

Let’s use an example to help you to understand the above table better.

Sub date_and_time()
date_example = Now()
Range("C1") = Format(date_example, "mm.dd.yy")
Range("C2") = Format(date_example, "d mmmmyyyy")
Range("C3") = Format(date_example, "mmmm j, yyyy")
Range("C4") = Format(date_example, "ddddd")
Range("C5") = Format(date_example, "mmmm-yy")
Range("C6") = Format(date_example, "mm.dd.yyyyhh:mm")
Range("C7") = Format(date_example, "m.d.yy h:mm AM/PM")
Range("C8") = Format(date_example, "hHmm")
End Sub

In this program we assign the system date and time through the now() to the variable date_example. After the execution of the program, the cells will contain the following values

C1 will contain 03.24.14
C2 will contain 24 March 2014
C3 will contain March 24 2014
C4 will contain Mon 24
C5 will contain March-14
C6 will contain 03.24.2014 15:04
C7 will contain 3.24.14 15:04 PM
C8 will contain 15H04

Given below is an example of using date function to calculate your age. We assume that you have basic programming knowledge. If not please refer our basic tutorial on VBA programming.

Calculating Age In VBA

Function Age(Date1 As Date, Date2 As Date) As String
Dim Year1 As Integer
Dim Month_1 As Integer
Dim Day1 As Integer
Dim Temp As Date
Temp = DateSerial(Year(Date2), Month(Date1), Day(Date1))
Year1 = Year(Date2) - Year(Date1) + (Temp > Date2)
Month1 = Month(Date2) - Month(Date1) - (12 * (Temp > Date2))
Day1 = Day(Date2) - Day(Date1)
If Day1 < 0 Then
Month_1 = Month_1 - 1
Day1 = Day(DateSerial(Year(Date2), Month(Date2) + 1, 0)) + Day1 + 1
End If
Age = Year1 &“years "& Month_1 & " months " & Day1 & " days"
End Function

This program accepts two parameters Date1 and Date2. Date1 is the year of your birth and Date2 is the current date. In the end, you get your age in terms of years, months and days.

Like you’ve just seen, the Format function for date and time comes in variety of options. You can choose the format that you want to display or use in your programs. As always practice makes perfect. Do try these examples for yourself. If you’d like to get more hands on with VBA before  you proceed, this course can help you.  Once you’re ready to step it up a notch, you can try out this Ultimate VBA course. Let us know how it goes!

Понравилась статья? Поделить с друзьями:
  • Word vba текст в одну строку
  • Word vba текст абзаца
  • Word vba таблица с объединенными ячейками
  • Word vba регулярное выражение
  • Word vba поля field