Vba excel преобразование даты в число

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

Синтаксис функций преобразования

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

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

Функции преобразования типов

Наименования функций преобразования типов, типы возвращаемых данных, диапазоны допустимых значений для аргумента:

Функция Тип данных Диапазон значений аргумента
CBool Boolean Любое допустимое строковое или числовое выражение.
CByte Byte От 0 до 255.
CCur Currency От -922 337 203 685 477,5808 до 922 337 203 685 477,5807.
CDate Date Любое допустимое выражение даты.
CDbl Double От -1,79769313486231E308 до -4,94065645841247E-324 для отрицательных значений; от 4,94065645841247E-324 до 1,79769313486232E308 для положительных значений.
CDec Decimal 79 228 162 514 264 337 593 543 950 335 для чисел без десятичных знаков. Для чисел с 28 десятичными знаками диапазон составляет 7,9228162514264337593543950335. Наименьшим возможным числом, отличным от нуля, является число 0,0000000000000000000000000001.
CInt Integer От -32 768 до 32 767, дробная часть округляется.
CLng Long От -2 147 483 648 до 2 147 483 647, дробная часть округляется.
CSng Single От -3,402823E38 до -1,401298E-45 для отрицательных значений; от 1,401298E-45 до 3,402823E38 для положительных значений.
CStr String Результат, возвращаемый функцией CStr, зависит от аргумента Выражение.
CVar Variant Диапазон совпадает с типом Double  для числовых значений и с типом  String  для нечисловых значений.

Дополнительно для VBA7:

Функция Тип данных Диапазон значений аргумента
CLngLng LongLong От -9 223 372 036 854 775 808 до 9 223 372 036 854 775 807, дробная часть округляется. Действительно только для 64-разрядных платформ.
CLngPtr LongPtr От -2 147 483 648 до 2 147 483 647 для 32-разрядных платформ, от -9 223 372 036 854 775 808 до 9 223 372 036 854 775 807 для 64-разрядных платформ, дробная часть округляется в обоих типах систем.

Примеры преобразования типов

Функция CBool

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

Dim a

a = CBool(10) ‘Результат: True

a = CBool(0) ‘Результат: False

a = CBool(«True») ‘Результат: True

a = CBool(«Test») ‘Результат: Error

Dim a, b, c

a = «Test1»

b = «Test2»

c = CBool(a = b) ‘Результат: False

c = CBool(a <> b) ‘Результат: True

Функция CByte

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

Dim a, b, c

a = 654

b = 3.36

c = a / b ‘Результат: 194,642857142857

c = CByte(c) ‘Результат: 195

c = a * b ‘Результат: 2197,44

c = CByte(c) ‘Результат: Error

Функция CCur

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

Dim a, b, c

a = 254.6598254

b = 569.2156843

c = a + b ‘Результат: 823,8755097

c = CCur(a + b) ‘Результат: 823,8755

Функция CDate

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

Dim a As String, b As Date, c As Double

a = «28.01.2021»

b = CDate(a) ‘Результат: #28.01.2021#

c = CDbl(b) ‘Результат: 44224

Dim a

a = CDate(44298.63895) ‘Результат: #12.04.2021 15:20:05#

a = CDate(44298) ‘Результат: #12.04.2021#

a = CDate(0.63895) ‘Результат: #15:20:05#

Функция CDbl

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

Dim a As String, b As String, c As Double

a = «45,3695423»

b = «548955,756»

c = CDbl(a) + CDbl(b) ‘Результат: 549001,1255423

Примечание
Eсли основной язык системы – русский, при записи в редакторе VBA Excel дробного числа в виде текста, ставим в качестве разделителя десятичных разрядов – запятую. Проверьте разделитель по умолчанию для своей национальной системы:
MsgBox Application.DecimalSeparator

Функция CDec

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

Dim a As String, b As Double, c

a = «5,9228162514264337593543950335»

b = 5.92281625142643

c = CDec(a) CDec(b) ‘Результат: 0,0000000000000037593543950335

Dim a As Double, b As String, c

a = 4.2643E14

b = CStr(a) ‘Результат: «4,2643E-14»

c = CDec(a) ‘Результат: 0,000000000000042643

Функция CInt

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

Dim a As String, b As Integer

a = «2355,9228»

b = CInt(a) ‘Результат: 2356

Функция CLng

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

Dim a As Date, b As Long

a = CDate(44298.63895) ‘Результат: #12.04.2021 15:20:05#

b = CLng(a) ‘Результат: 44299

a = CDate(b) ‘Результат: #13.04.2021#

Функция CSng

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

Dim a As String, b As Single

a = «3,2365625106»

b = CSng(a) ‘Результат: 3,236562

Функция CStr

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

Dim a As Single, b As String

a = 5106.23

b = CStr(a) ‘Результат: «5106,23»

Функция CVar

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

Dim a As Double, b As String, c

a = 549258.232546

b = «Новое сообщение»

c = CVar(a) ‘Результат: 549258,232546 (Variant/Double)

c = CVar(b) ‘Результат: «Новое сообщение» (Variant/String)

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


0 / 0 / 0

Регистрация: 04.04.2019

Сообщений: 54

1

Excel

Преобразовать дату в число

21.05.2019, 14:16. Показов 15094. Ответов 3


Студворк — интернет-сервис помощи студентам

Есть дата в переменной в формате «01.02.3088» как ее преобразовать в число 433941 ?
То есть просто cells().numberformat = “@“. Но как это сделать в переменной, не изменяя ячейку?



0



Programming

Эксперт

94731 / 64177 / 26122

Регистрация: 12.04.2006

Сообщений: 116,782

21.05.2019, 14:16

3

ArtNord

370 / 268 / 93

Регистрация: 18.11.2015

Сообщений: 990

21.05.2019, 14:26

2

Попробуйте так:

Visual Basic
1
2
3
а =cells(b,c)
a=a*1
cells(b,c) = a

Добавлено через 8 минут

Цитата
Сообщение от ArtNord
Посмотреть сообщение

3
а =cells(b,c)
a=a*1
cells(b,c) = «‘»&a

Точнее так, но число станет текстом



0



Kate_27

198 / 132 / 67

Регистрация: 27.03.2019

Сообщений: 288

21.05.2019, 14:34

3

Лучший ответ Сообщение было отмечено Sadma1 как решение

Решение

Sadma1, Может Вам обратить внимание на функцию CLng?

Visual Basic
1
2
3
4
5
Sub DateInLong()
    Dim A As Date
    A = Cells(1, 1)
    Cells(2, 1) = CLng(A)
End Sub



1



pashulka

4131 / 2235 / 940

Регистрация: 01.12.2010

Сообщений: 4,624

21.05.2019, 18:19

4

Sadma1, Если дата изначально хранится в ячейке, то можно использовать свойство Value2

Visual Basic
1
2
3
Cells(1) = Date 'для наглядности
dt = Cells(1).Value2
MsgBox dt



0



 

Boris05036

Пользователь

Сообщений: 42
Регистрация: 12.03.2016

Доброго времени суток! Форумчане, уже мозг взорвался, перепробовал несколько методов, предложенных когда-то на разных форумах.
В файле вырезал нужный кусок. Сделать надо именно в vba, т.к. это часть макроса… из-за этого он некорректно проводит сортировку по дате.
верхние даты скопированы из одного файла, нижние из другого, поэтому оказалось, что вверху текстовый формат, внизу числовой формат даты…

 

Kuzmich

Пользователь

Сообщений: 7998
Регистрация: 21.12.2012

#2

25.07.2016 16:39:48

UDF

Код
Function iDate(cell As String) As Date
  iDate = CDate(cell)
End Function
 

JayBhagavan

Пользователь

Сообщений: 11833
Регистрация: 17.01.2014

ПОЛ: МУЖСКОЙ | Win10x64, MSO2019x64

#3

25.07.2016 16:47:20

Код
Sub jjj()
    Dim cl As Range
    
    Selection.NumberFormat = "m/d/yyyy"
    Selection.HorizontalAlignment = xlGeneral
    For Each cl In Selection
        cl.Value = CDate(cl.Value)
    Next cl
End Sub

<#0>
Формула массива (ФМ) вводится Ctrl+Shift+Enter
Memento mori

 

Boris05036

Пользователь

Сообщений: 42
Регистрация: 12.03.2016

JayBhagavan, спасибо, вроде это сработало, но я задам еще один вопрос. С форматом теперь все нормально, но сортировка не идет… кто-нибудь может определить почему?

 

Kuzmich

Пользователь

Сообщений: 7998
Регистрация: 21.12.2012

А мой вариант, что не подошел?

 

Boris05036

Пользователь

Сообщений: 42
Регистрация: 12.03.2016

Kuzmich, и вам спасибо, тут однократно решил воспользоваться вторым вариантом, но суть одна ведь.

 

Kuzmich

Пользователь

Сообщений: 7998
Регистрация: 21.12.2012

#7

25.07.2016 18:59:57

Цитата
но сортировка не идет… кто-нибудь может определить почему?

Уберите структуру

 

Boris05036

Пользователь

Сообщений: 42
Регистрация: 12.03.2016

Kuzmich, что вы имеете в виду?

 

Kuzmich

Пользователь

Сообщений: 7998
Регистрация: 21.12.2012

Данные — группа и структура — разгруппировать

 

Boris05036

Пользователь

Сообщений: 42
Регистрация: 12.03.2016

#10

25.07.2016 19:46:53

Kuzmich, спасибо, попробую, этого я и не заметил, притекло из другого файла

Преобразование даты в число и наоборот

Elhust

Дата: Понедельник, 15.05.2017, 08:40 |
Сообщение № 1

Группа: Проверенные

Ранг: Форумчанин

Сообщений: 184


Репутация:

-1

±

Замечаний:
0% ±


Excel 2010

Добрый день увожаемые специалисты и просто гуру excel
Возникла такая задача у меня есть три отдельных числа:
-день в виде «2»
-месяц в виде «7»
-год в виде «2014»
и с помощью DateSerial я преобразую в дату
[vba]

Код

Dim DateExpert as String
iCell34=2014
iCell33=7
iCell32=2
DateExpert = DateSerial(iCell34, iCell33, iCell32)
MsgBox DateExpert

[/vba]
всё хорошо но вот с помощью DateValue преобразовать в число не удаётся … это мне надо чтобы выявить минимальную дату или наименьшую дату
Благодарю за внимание


Каждый сам выбирает правила игры

 

Ответить

nilem

Дата: Понедельник, 15.05.2017, 09:14 |
Сообщение № 2

Группа: Авторы

Ранг: Старожил

Сообщений: 1612


Репутация:

563

±

Замечаний:
0% ±


Excel 2013, 2016

Даты — это ведь и есть число. «выявить минимальную дату или наименьшую дату » — выявляйте как с обычными числами.
вот здесь
[vba]

Код

Dim DateExpert as String

[/vba]
нужно As Date


Яндекс.Деньги 4100159601573

 

Ответить

Elhust

Дата: Понедельник, 15.05.2017, 09:30 |
Сообщение № 3

Группа: Проверенные

Ранг: Форумчанин

Сообщений: 184


Репутация:

-1

±

Замечаний:
0% ±


Excel 2010

nilem,
То есть я ставлю тип данных Date и вычисляю по методу
[vba]

Код

Dim DateExpert as Date, DateExpert1 as Date
Dim Mindate as Double
iCell34=2014
iCell33=7
iCell32=2
iCell35=2013
iCell36=7
iCell37=2
DateExpert = DateSerial(iCell34, iCell33, iCell32)
DateExpert1 = DateSerial(iCell35, iCell36, iCell37)
Mindate = Application.WorksheetFunction.Min(DateExpert ,DateExpert1 )
MsgBox Mindate

[/vba]


Каждый сам выбирает правила игры

Сообщение отредактировал ElhustПонедельник, 15.05.2017, 09:34

 

Ответить

Elhust

Дата: Понедельник, 15.05.2017, 09:33 |
Сообщение № 4

Группа: Проверенные

Ранг: Форумчанин

Сообщений: 184


Репутация:

-1

±

Замечаний:
0% ±


Excel 2010

nilem, слушай а если такая загвоздка как посчитать минимальное значение если ты не в рабочей книге а в активной книге ? а то у меня цикл по книгам в папке


Каждый сам выбирает правила игры

 

Ответить

nilem

Дата: Понедельник, 15.05.2017, 09:34 |
Сообщение № 5

Группа: Авторы

Ранг: Старожил

Сообщений: 1612


Репутация:

563

±

Замечаний:
0% ±


Excel 2013, 2016

ну да
только Mindate as Date — это для сообщения №3 (не успеваю :)


Яндекс.Деньги 4100159601573

Сообщение отредактировал nilemПонедельник, 15.05.2017, 09:35

 

Ответить

Elhust

Дата: Понедельник, 15.05.2017, 09:41 |
Сообщение № 6

Группа: Проверенные

Ранг: Форумчанин

Сообщений: 184


Репутация:

-1

±

Замечаний:
0% ±


Excel 2010

nilem, Акей слушай но у меня и с Double выводиться ) правда преобразуется дата в вид 45452 ^_^


Каждый сам выбирает правила игры

Сообщение отредактировал ElhustПонедельник, 15.05.2017, 09:41

 

Ответить

nilem

Дата: Понедельник, 15.05.2017, 09:43 |
Сообщение № 7

Группа: Авторы

Ранг: Старожил

Сообщений: 1612


Репутация:

563

±

Замечаний:
0% ±


Excel 2013, 2016

«в вид 45452» — потому что дата — это число, вот Double и показывает число. А если объявить как Date, то покажет нормальную дату (вернее, число в формате даты)
Если выбирать мин дату из нескольких книг, то попробуйте как-то так
[vba]

Код

Dim DateExpert As Date
DateExpert = #5/15/2159# ‘назначаем заранее какую-то большую дату

Dim dt As Date

Цикл по книгам

    dt = DateSerial(2014, 7, 2) ‘эту дату берем из книги
    If dt < DateExpert Then DateExpert = dt

Next

MsgBox «минимальная дата в книгах » & DateExpert

[/vba]


Яндекс.Деньги 4100159601573

Сообщение отредактировал nilemПонедельник, 15.05.2017, 09:44

 

Ответить

Elhust

Дата: Понедельник, 15.05.2017, 09:47 |
Сообщение № 8

Группа: Проверенные

Ранг: Форумчанин

Сообщений: 184


Репутация:

-1

±

Замечаний:
0% ±


Excel 2010

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


Каждый сам выбирает правила игры

Сообщение отредактировал ElhustПонедельник, 15.05.2017, 09:49

 

Ответить

nilem

Дата: Понедельник, 15.05.2017, 09:53 |
Сообщение № 9

Группа: Авторы

Ранг: Старожил

Сообщений: 1612


Репутация:

563

±

Замечаний:
0% ±


Excel 2013, 2016

А, ну тогда да, просто Worksheetfunction.Min(какие-то даты)
какие-то даты — из активной книги (которая сейчас открыта в цикле)


Яндекс.Деньги 4100159601573

Сообщение отредактировал nilemПонедельник, 15.05.2017, 09:56

 

Ответить

Elhust

Дата: Понедельник, 15.05.2017, 10:01 |
Сообщение № 10

Группа: Проверенные

Ранг: Форумчанин

Сообщений: 184


Репутация:

-1

±

Замечаний:
0% ±


Excel 2010

nilem, Вот вроде всё хорошо но ошибка «Невозможно получить свойство Min класса WorksheetFunction» 1004


Каждый сам выбирает правила игры

 

Ответить

nilem

Дата: Понедельник, 15.05.2017, 10:30 |
Сообщение № 11

Группа: Авторы

Ранг: Старожил

Сообщений: 1612


Репутация:

563

±

Замечаний:
0% ±


Excel 2013, 2016

Тогда нужен пример файла. И код, который с этим файлом работает.


Яндекс.Деньги 4100159601573

 

Ответить

Michael_S

Дата: Понедельник, 15.05.2017, 11:05 |
Сообщение № 12

Группа: Друзья

Ранг: Старожил

Сообщений: 2012


Репутация:

373

±

Замечаний:
0% ±


Excel2016


Elhust, вы 90 года, а Николай (nilem,) — 67… разница более 20 лет… Да и вообще, у нас на форуме приято общаться на «вы».
Это я еще могу Коле сказать «ты», как и он мне — мы друг друга давно знаем, но и то, по привычке обычно говорим «вы».
Извините за нравоучения.

 

Ответить

Elhust

Дата: Понедельник, 15.05.2017, 11:41 |
Сообщение № 13

Группа: Проверенные

Ранг: Форумчанин

Сообщений: 184


Репутация:

-1

±

Замечаний:
0% ±


Excel 2010

nilem, Michael_S, Прошу прощения если кого задел … буду держаться за правила впредь


Каждый сам выбирает правила игры

 

Ответить

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 excel предыдущее значение ячейки
  • Vba excel правый символ
  • Vba excel пошаговое выполнение макроса
  • Vba excel посчитать непустые ячейки
  • Vba excel получить путь к папке