Содержание
- Vba excel строка с числами
- Функция Val
- Синтаксис
- Замечания
- Пример
- См. также
- Поддержка и обратная связь
- Функция Str
- Синтаксис
- Замечания
- Пример
- См. также
- Поддержка и обратная связь
- Type conversion functions
- Syntax
- Return types
- Remarks
- CBool function example
- CByte function example
- CCur function example
- CDate function example
- CDbl function example
- CDec function example
- CInt function example
- CLng function example
- CSng function example
- CStr function example
- CVar function example
- See also
- Support and feedback
Vba excel строка с числами
На этом шаге мы перечислим функции преобразования форматов .
Преобразование строки в число и обратно осуществляют следующими функциями.
Функция | Назначение |
---|---|
Val ( строка ) | Возвращает числа, содержащиеся в строке, как числовое значение соответствующего типа |
Str ( число ) | Возвращает значение типа Variant (String) , являющееся строковым представлением числа |
Таблица 1. Преобразование строки в число и обратно
В качестве допустимого десятичного разделителя функция Str воспринимает только точку. При наличии другого десятичного разделителя (например, запятой) для преобразования чисел в строки следует использовать функцию CStr , указанную в конце этого шага.
Чтобы представить числовое значение как дату, время, денежное значение или в специальном формате, следует использовать функцию Format .
Функция Format возвращает значение типа Variant (String) , содержащее выражение, отформатированное согласно инструкциям, заданным в описании формата. Синтаксис:
При построении пользовательского числового формата возможно использование следующих символов.
Символ | Назначение |
---|---|
0 | Резервирует позицию цифрового разряда. Отображает цифру или нуль. Если у числа, представленного аргументом, есть какая-нибудь цифра в той позиции разряда, где в строке формата находится 0, функция отображает эту цифру аргумента, если нет — в этой позиции отображается нуль |
# | Резервирует позицию цифрового разряда. Отображает цифру или ничего не отображает. Если у числа, представленного аргументом, есть какая-нибудь цифра в той позиции разряда, где в строке формата находится #, функция отображает эту цифру аргумента, если нет — в исходной позиции не отображается ничего. Действие данного символа аналогично действию 0, за исключением того, что лидирующие нули не отображаются |
. ( точка ) | Резервирует позицию десятичного разделителя. Указание точки в строке формата определяет, сколько разрядов необходимо отображать слева и справа от десятичной точки |
% | Резервирует процентное отображение числа |
, | Разделитель разряда сотен от тысяч |
: | Разделитель часов, минут и секунд в категории форматов Время (Time) |
/ | Разделитель дня, месяца и года в категории форматов Дата (Date) |
E+, E-, e+, e- | Разделитель мантиссы и порядка в экспоненциальном формате |
Таблица 2. Символы, используемые в числовом формате
Кроме функций Val и Str в VBA имеются следующие функции преобразования типов выражений из данного в указанный.
Функция | Тип, в который преобразуется выражение |
---|---|
CBool ( Выражение ) | Boolean |
CByte ( Выражение ) | Byte |
CCur ( Выражение ) | Currency |
CDate ( Выражение ) | Date |
СDbl ( Выражение ) | Double |
CDec ( Выражение ) | Decimal |
CInt ( Выражение ) | Integer |
CLng ( Выражение ) | Long |
CSng ( Выражение ) | Single |
CVar ( Выражение ) | Variant |
CStr ( Выражение ) | String |
Таблица 3. Функции преобразования форматов
На следующем шаге мы рассмотрим функции обработки строк .
Источник
Функция Val
Возвращает числа, содержащиеся в строке, как числовое значение соответствующего типа.
Синтаксис
Val(string)
Замечания
Функция Val перестает считывать строку на первом символе, который она не может распознать как часть числа. Символы и знаки, которые обычно считаются частью числа (например, знак доллара и запятая), не распознаются.
Однако функция распознает префиксы &O радикса (для восьмерицы) и &H (для шестнадцатеричных). Пробелы, символы табуляции и знаки перевода строк удаляются из значения аргумента.
В следующем примере возвращается значение 1615198:
В следующем коде Val возвращает десятичное значение -1 для показанного шестнадцатеричного значения:
Функция Val распознает только точку ( . ) в качестве допустимого десятичного разделителя. При использовании различных десятичных разделителей (например, в национальных версиях приложений), используйте CDbl для преобразования строки в число.
Пример
В этом примере функция Val возвращает числа, содержащиеся в строке.
Функция Val распознает устаревшие суффиксы типа данных до преобразования и может привести к ошибке несоответствия типов. Например, пятьдесят процентов, представленных как строка «50%», преобразуются, как ожидается, в 50, но Val(«50,5%») вызовет ошибку, так как символ процента рассматривается как суффикс для объявления типа данных в виде целого числа, которого в данном случае нет. Полный список суффиксов типа данных включает одинарный ( ! ), currency ( @ ), double ( # ), string ( $ ), Integer ( % ), Long ( & ) и LongLong ( ^ ) для 64-разрядных узлов.
См. также
Поддержка и обратная связь
Есть вопросы или отзывы, касающиеся Office VBA или этой статьи? Руководство по другим способам получения поддержки и отправки отзывов см. в статье Поддержка Office VBA и обратная связь.
Источник
Функция Str
Возвращает представление числа в виде Variant (String).
Синтаксис
Str(number)
Обязательный аргумент number — это long, содержащий любое допустимое числовое выражение.
Замечания
При преобразовании чисел в строки начальный пробел всегда резервируется для добавления знака числа. Для положительного числа возвращается строка с начальным пробелом (в этом случае подразумевается наличие знака плюса).
Используйте функцию Формат для преобразования числовых значений, которые необходимо отформатировать в виде дат, времени или валюты или в других определяемых пользователем форматах. В отличие от функции Str, функция Format не добавляет начальный пробел для знака числа.
Функция Str распознает только точку ( . ) в качестве допустимого десятичного разделителя. В международных приложениях, в которых используются другие десятичные разделители, для преобразования чисел в строки используйте функции CStr.
Пример
В этом примере функция Str возвращает строковое представление числа. При преобразовании числа в строку всегда резервируется начальный пробел для знака.
См. также
Поддержка и обратная связь
Есть вопросы или отзывы, касающиеся Office VBA или этой статьи? Руководство по другим способам получения поддержки и отправки отзывов см. в статье Поддержка Office VBA и обратная связь.
Источник
Type conversion functions
Each function coerces an expression to a specific data type.
Syntax
- CBool(expression)
- CByte(expression)
- CCur(expression)
- CDate(expression)
- CDbl(expression)
- CDec(expression)
- CInt(expression)
- CLng(expression)
- CLngLng(expression) (Valid on 64-bit platforms only.)
- CLngPtr(expression)
- CSng(expression)
- CStr(expression)
- CVar(expression)
The required expression argument is any string expression or numeric expression.
Return types
The function name determines the return type as shown in the following:
Function | Return type | Range for expression argument |
---|---|---|
CBool | Boolean | Any valid string or numeric expression. |
CByte | Byte | 0 to 255. |
CCur | Currency | -922,337,203,685,477.5808 to 922,337,203,685,477.5807. |
CDate | Date | Any valid date expression. |
CDbl | Double | -1.79769313486231E308 to -4.94065645841247E-324 for negative values; 4.94065645841247E-324 to 1.79769313486232E308 for positive values. |
CDec | Decimal | 79,228,162,514,264,337,593,543,950,335 for zero-scaled numbers, that is, numbers with no decimal places. For numbers with 28 decimal places, the range is 7.9228162514264337593543950335. The smallest possible non-zero number is 0.0000000000000000000000000001. |
CInt | Integer | -32,768 to 32,767; fractions are rounded. |
CLng | Long | -2,147,483,648 to 2,147,483,647; fractions are rounded. |
CLngLng | LongLong | -9,223,372,036,854,775,808 to 9,223,372,036,854,775,807; fractions are rounded. (Valid on 64-bit platforms only.) |
CLngPtr | LongPtr | -2,147,483,648 to 2,147,483,647 on 32-bit systems, -9,223,372,036,854,775,808 to 9,223,372,036,854,775,807 on 64-bit systems; fractions are rounded for 32-bit and 64-bit systems. |
CSng | Single | -3.402823E38 to -1.401298E-45 for negative values; 1.401298E-45 to 3.402823E38 for positive values. |
CStr | String | Returns for CStr depend on the expression argument. |
CVar | Variant | Same range as Double for numerics. Same range as String for non-numerics. |
If the expression passed to the function is outside the range of the data type being converted to, an error occurs.
Conversion functions must be used to explicitly assign LongLong (including LongPtr on 64-bit platforms) to smaller integral types. Implicit conversions of LongLong to smaller integrals are not allowed.
In general, you can document your code using the data-type conversion functions to show that the result of some operation should be expressed as a particular data type rather than the default data type. For example, use CCur to force currency arithmetic in cases where single-precision, double-precision, or integer arithmetic normally would occur.
You should use the data-type conversion functions instead of Val to provide internationally aware conversions from one data type to another. For example, when you use CCur, different decimal separators, different thousand separators, and various currency options are properly recognized depending on the locale setting of your computer.
When the fractional part is exactly 0.5, CInt and CLng always round it to the nearest even number. For example, 0.5 rounds to 0, and 1.5 rounds to 2. CInt and CLng differ from the Fix and Int functions, which truncate, rather than round, the fractional part of a number. Also, Fix and Int always return a value of the same type as is passed in.
Use the IsDate function to determine if date can be converted to a date or time. CDate recognizes date literals and time literals as well as some numbers that fall within the range of acceptable dates. When converting a number to a date, the whole number portion is converted to a date. Any fractional part of the number is converted to a time of day, starting at midnight.
CDate recognizes date formats according to the locale setting of your system. The correct order of day, month, and year may not be determined if it is provided in a format other than one of the recognized date settings. In addition, a long date format is not recognized if it also contains the day-of-the-week string.
A CVDate function is also provided for compatibility with previous versions of Visual Basic. The syntax of the CVDate function is identical to the CDate function; however, CVDate returns a Variant whose subtype is Date instead of an actual Date type. Since there is now an intrinsic Date type, there is no further need for CVDate. The same effect can be achieved by converting an expression to a Date, and then assigning it to a Variant. This technique is consistent with the conversion of all other intrinsic types to their equivalent Variant subtypes.
The CDec function does not return a discrete data type; instead, it always returns a Variant whose value has been converted to a Decimal subtype.
CBool function example
This example uses the CBool function to convert an expression to a Boolean. If the expression evaluates to a nonzero value, CBool returns True, otherwise, it returns False.
CByte function example
This example uses the CByte function to convert an expression to a Byte.
CCur function example
This example uses the CCur function to convert an expression to a Currency.
CDate function example
This example uses the CDate function to convert a string to a Date. In general, hard-coding dates and times as strings (as shown in this example) is not recommended. Use date literals and time literals, such as #2/12/1969# and #4:45:23 PM# , instead.
CDbl function example
This example uses the CDbl function to convert an expression to a Double.
CDec function example
This example uses the CDec function to convert a numeric value to a Decimal.
CInt function example
This example uses the CInt function to convert a value to an Integer.
CLng function example
This example uses the CLng function to convert a value to a Long.
CSng function example
This example uses the CSng function to convert a value to a Single.
CStr function example
This example uses the CStr function to convert a numeric value to a String.
CVar function example
This example uses the CVar function to convert an expression to a Variant.
See also
Support and feedback
Have questions or feedback about Office VBA or this documentation? Please see Office VBA support and feedback for guidance about the ways you can receive support and provide feedback.
Источник
Функции преобразования типов данных в 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.2643E—14 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 для того, чтобы указать, что результатом выполнения той или иной операции должны стать данные определенного типа, отличающегося от типа, заданного по умолчанию.
In this Article
- Formatting Numbers in Excel VBA
- How to Use the Format Function in VBA
- Creating a Format String
- Using a Format String for Alignment
- Using Literal Characters Within the Format String
- Use of Commas in a Format String
- Creating Conditional Formatting within the Format String
- Using Fractions in Formatting Strings
- Date and Time Formats
- Predefined Formats
- General Number
- Currency
- Fixed
- Standard
- Percent
- Scientific
- Yes/No
- True/False
- On/Off
- General Date
- Long Date
- Medium Date
- Short Date
- Long Time
- Medium Time
- Short Time
- Dangers of Using Excel’s Pre-Defined Formats in Dates and Times
- User-Defined Formats for Numbers
- User-Defined Formats for Dates and Times
Formatting Numbers in Excel VBA
Numbers come in all kinds of formats in Excel worksheets. You may already be familiar with the pop-up window in Excel for making use of different numerical formats:
Formatting of numbers make the numbers easier to read and understand. The Excel default for numbers entered into cells is ‘General’ format, which means that the number is displayed exactly as you typed it in.
For example, if you enter a round number e.g. 4238, it will be displayed as 4238 with no decimal point or thousands separators. A decimal number such as 9325.89 will be displayed with the decimal point and the decimals. This means that it will not line up in the column with the round numbers, and will look extremely messy.
Also, without showing the thousands separators, it is difficult to see how large a number actually is without counting the individual digits. Is it in millions or tens of millions?
From the point of view of a user looking down a column of numbers, this makes it quite difficult to read and compare.
In VBA you have access to exactly the same range of formats that you have on the front end of Excel. This applies to not only an entered value in a cell on a worksheet, but also things like message boxes, UserForm controls, charts and graphs, and the Excel status bar at the bottom left hand corner of the worksheet.
The Format function is an extremely useful function in VBA in presentation terms, but it is also very complex in terms of the flexibility offered in how numbers are displayed.
How to Use the Format Function in VBA
If you are showing a message box, then the Format function can be used directly:
MsgBox Format(1234567.89, "#,##0.00")
This will display a large number using commas to separate the thousands and to show 2 decimal places. The result will be 1,234,567.89. The zeros in place of the hash ensure that decimals will be shown as 00 in whole numbers, and that there is a leading zero for a number which is less than 1
The hashtag symbol (#) represents a digit placeholder which displays a digit if it is available in that position, or else nothing.
You can also use the format function to address an individual cell, or a range of cells to change the format:
Sheets("Sheet1").Range("A1:A10").NumberFormat = "#,##0.00"
This code will set the range of cells (A1 to A10) to a custom format which separates the thousands with commas and shows 2 decimal places.
If you check the format of the cells on the Excel front end, you will find that a new custom format has been created.
You can also format numbers on the Excel Status Bar at the bottom left hand corner of the Excel window:
Application.StatusBar = Format(1234567.89, "#,##0.00")
You clear this from the status bar by using:
Application.StatusBar = ""
Creating a Format String
This example will add the text ‘Total Sales’ after each number, as well as including a thousands separator
Sheets("Sheet1").Range("A1:A6").NumberFormat = "#,##0.00"" Total Sales"""
This is what your numbers will look like:
Note that cell A6 has a ‘SUM’ formula, and this will include the ‘Total Sales’ text without requiring formatting. If the formatting is applied, as in the above code, it will not put an extra instance of ‘Total Sales’ into cell A6
Although the cells now display alpha numeric characters, the numbers are still present in numeric form. The ‘SUM’ formula still works because it is using the numeric value in the background, not how the number is formatted.
The comma in the format string provides the thousands separator. Note that you only need to put this in the string once. If the number runs into millions or billions, it will still separate the digits into groups of 3
The zero in the format string (0) is a digit placeholder. It displays a digit if it is there, or a zero. Its positioning is very important to ensure uniformity with the formatting
In the format string, the hash characters (#) will display nothing if there is no digit. However, if there is a number like .8 (all decimals), we want it to show as 0.80 so that it lines up with the other numbers.
By using a single zero to the left of the decimal point and two zeros to the right of the decimal point in the format string, this will give the required result (0.80).
If there was only one zero to the right of the decimal point, then the result would be ‘0.8’ and everything would be displayed to one decimal place.
Using a Format String for Alignment
We may want to see all the decimal numbers in a range aligned on their decimal points, so that all the decimal points are directly under each other, however many places of decimals there are on each number.
You can use a question mark (?) within your format string to do this. The ‘?’ indicates that a number is shown if it is available, or a space
Sheets("Sheet1").Range("A1:A6").NumberFormat = "#,##0.00??"
This will display your numbers as follows:
All the decimal points now line up underneath each other. Cell A5 has three decimal places and this would throw the alignment out normally, but using the ‘?’ character aligns everything perfectly.
Using Literal Characters Within the Format String
You can add any literal character into your format string by preceding it with a backslash ().
Suppose that you want to show a particular currency indicator for your numbers which is not based on your locale. The problem is that if you use a currency indicator, Excel automatically refers to your local and changes it to the one appropriate for the locale that is set on the Windows Control Panel. This could have implications if your Excel application is being distributed in other countries and you want to ensure that whatever the locale is, the currency indicator is always the same.
You may also want to indicate that the numbers are in millions in the following example:
Sheets("Sheet1").Range("A1:A6").NumberFormat = "$#,##0.00 m"
This will produce the following results on your worksheet:
In using a backslash to display literal characters, you do not need to use a backslash for each individual character within a string. You can use:
Sheets("Sheet1").Range("A1:A6").NumberFormat = "$#,##0.00 mill"
This will display ‘mill’ after every number within the formatted range.
You can use most characters as literals, but not reserved characters such as 0, #,?
Use of Commas in a Format String
We have already seen that commas can be used to create thousands separators for large numbers, but they can also be used in another way.
By using them at the end of the numeric part of the format string, they act as scalers of thousands. In other words, they will divide each number by 1,000 every time there is a comma.
In the example data, we are showing it with an indicator that it is in millions. By inserting one comma into the format string, we can show those numbers divided by 1,000.
Sheets("Sheet1").Range("A1:A6").NumberFormat = "$#,##0.00,m"
This will show the numbers divided by 1,000 although the original number will still be in background in the cell.
If you put two commas in the format string, then the numbers will be divided by a million
Sheets("Sheet1").Range("A1:A6").NumberFormat = "$#,##0.00,,m"
This will be the result using only one comma (divide by 1,000):
VBA Coding Made Easy
Stop searching for VBA code online. Learn more about AutoMacro — A VBA Code Builder that allows beginners to code procedures from scratch with minimal coding knowledge and with many time-saving features for all users!
Learn More
Creating Conditional Formatting within the Format String
You could set up conditional formatting on the front end of Excel, but you can also do it within your VBA code, which means that you can manipulate the format string programmatically to make changes.
You can use up to four sections within your format string. Each section is delimited by a semicolon (;). The four sections correspond to positive, negative, zero, and text
Range("A1:A7").NumberFormat = "#,##0.00;[Red]-#,##0.00;[Green] #,##0.00;[Blue]”
In this example, we use the same hash, comma, and zero characters to provide thousand separators and two decimal points, but we now have different sections for each type of value.
The first section is for positive numbers and is no different to what we have already seen previously in terms of format.
The second section for negative numbers introduces a color (Red) which is held within a pair of square brackets. The format is the same as for positive numbers except that a minus (-) sign has been added in front.
The third section for zero numbers uses a color (Green) within square brackets with the numeric string the same as for positive numbers.
The final section is for text values, and all that this needs is a color (Blue) again within square brackets
This is the result of applying this format string:
You can go further with conditions within the format string. Suppose that you wanted to show every positive number above 10,000 as green, and every other number as red you could use this format string:
Range("A1:A7").NumberFormat = "[>=10000][Green]#,##0.00;[<10000][Red]#,##0.00"
This format string includes conditions for >=10000 set in square brackets so that green will only be used where the number is greater than or equal to 10000
This is the result:
Using Fractions in Formatting Strings
Fractions are not often used in spreadsheets, since they normally equate to decimals which everyone is familiar with.
However, sometimes they do serve a purpose. This example will display dollars and cents:
Range("A1:A7").NumberFormat = "#,##0 "" dollars and "" 00/100 "" cents """
This is the result that will be produced:
Remember that in spite of the numbers being displayed as text, they are still there in the background as numbers and all the Excel formulas can still be used on them.
Date and Time Formats
Dates are actually numbers and you can use formats on them in the same way as for numbers. If you format a date as a numeric number, you will see a large number to the left of the decimal point and a number of decimal places. The number to the left of the decimal point shows the number of days starting at 01-Jan-1900, and the decimal places show the time based on 24hrs
MsgBox Format(Now(), "dd-mmm-yyyy")
This will format the current date to show ’08-Jul-2020’. Using ‘mmm’ for the month displays the first three characters of the month name. If you want the full month name then you use ‘mmmm’
You can include times in your format string:
MsgBox Format(Now(), "dd-mmm-yyyy hh:mm AM/PM")
This will display ’08-Jul-2020 01:25 PM’
‘hh:mm’ represents hours and minutes and AM/PM uses a 12-hour clock as opposed to a 24-hour clock.
You can incorporate text characters into your format string:
MsgBox Format(Now(), "dd-mmm-yyyy hh:mm AM/PM"" today""")
This will display ’08-Jul-2020 01:25 PM today’
You can also use literal characters using a backslash in front in the same way as for numeric format strings.
VBA Programming | Code Generator does work for you!
Predefined Formats
Excel has a number of built-in formats for both numbers and dates that you can use in your code. These mainly reflect what is available on the number formatting front end, although some of them go beyond what is normally available on the pop-up window. Also, you do not have the flexibility over number of decimal places, or whether thousands separators are used.
General Number
This format will display the number exactly as it is
MsgBox Format(1234567.89, "General Number")
The result will be 1234567.89
Currency
MsgBox Format(1234567.894, "Currency")
This format will add a currency symbol in front of the number e.g. $, £ depending on your locale, but it will also format the number to 2 decimal places and will separate the thousands with commas.
The result will be $1,234,567.89
Fixed
MsgBox Format(1234567.894, "Fixed")
This format displays at least one digit to the left but only two digits to the right of the decimal point.
The result will be 1234567.89
Standard
MsgBox Format(1234567.894, "Standard")
This displays the number with the thousand separators, but only to two decimal places.
The result will be 1,234,567.89
AutoMacro | Ultimate VBA Add-in | Click for Free Trial!
Percent
MsgBox Format(1234567.894, "Percent")
The number is multiplied by 100 and a percentage symbol (%) is added at the end of the number. The format displays to 2 decimal places
The result will be 123456789.40%
Scientific
MsgBox Format(1234567.894, "Scientific")
This converts the number to Exponential format
The result will be 1.23E+06
Yes/No
MsgBox Format(1234567.894, "Yes/No")
This displays ‘No’ if the number is zero, otherwise displays ‘Yes’
The result will be ‘Yes’
True/False
MsgBox Format(1234567.894, "True/False")
This displays ‘False’ if the number is zero, otherwise displays ‘True’
The result will be ‘True’
AutoMacro | Ultimate VBA Add-in | Click for Free Trial!
On/Off
MsgBox Format(1234567.894, "On/Off")
This displays ‘Off’ if the number is zero, otherwise displays ‘On’
The result will be ‘On’
General Date
MsgBox Format(Now(), "General Date")
This will display the date as date and time using AM/PM notation. How the date is displayed depends on your settings in the Windows Control Panel (Clock and Region | Region). It may be displayed as ‘mm/dd/yyyy’ or ‘dd/mm/yyyy’
The result will be ‘7/7/2020 3:48:25 PM’
Long Date
MsgBox Format(Now(), "Long Date")
This will display a long date as defined in the Windows Control Panel (Clock and Region | Region). Note that it does not include the time.
The result will be ‘Tuesday, July 7, 2020’
Medium Date
MsgBox Format(Now(), "Medium Date")
This displays a date as defined in the short date settings as defined by locale in the Windows Control Panel.
The result will be ’07-Jul-20’
AutoMacro | Ultimate VBA Add-in | Click for Free Trial!
Short Date
MsgBox Format(Now(), "Short Date")
Displays a short date as defined in the Windows Control Panel (Clock and Region | Region). How the date is displayed depends on your locale. It may be displayed as ‘mm/dd/yyyy’ or ‘dd/mm/yyyy’
The result will be ‘7/7/2020’
Long Time
MsgBox Format(Now(), "Long Time")
Displays a long time as defined in Windows Control Panel (Clock and Region | Region).
The result will be ‘4:11:39 PM’
Medium Time
MsgBox Format(Now(), "Medium Time")
Displays a medium time as defined by your locale in the Windows Control Panel. This is usually set as 12-hour format using hours, minutes, and seconds and the AM/PM format.
The result will be ’04:15 PM’
Short Time
MsgBox Format(Now(), "Short Time")
Displays a medium time as defined in Windows Control Panel (Clock and Region | Region). This is usually set as 24-hour format with hours and minutes
The result will be ’16:18’
AutoMacro | Ultimate VBA Add-in | Click for Free Trial!
Dangers of Using Excel’s Pre-Defined Formats in Dates and Times
The use of the pre-defined formats for dates and times in Excel VBA is very dependent on the settings in the Windows Control Panel and also what the locale is set to
Users can easily alter these settings, and this will have an effect on how your dates and times are displayed in Excel
For example, if you develop an Excel application which uses pre-defined formats within your VBA code, these may change completely if a user is in a different country or using a different locale to you. You may find that column widths do not fit the date definition, or on a user form the Active X control such as a combo box (drop down) control is too narrow for the dates and times to be displayed properly.
You need to consider where the audience is geographically when you develop your Excel application
User-Defined Formats for Numbers
There are a number of different parameters that you can use when defining your format string:
Character | Description |
Null String | No formatting |
0 | Digit placeholder. Displays a digit or a zero. If there is a digit for that position then it displays the digit otherwise it displays 0. If there are fewer digits than zeros, then you will get leading or trailing zeros. If there are more digits after the decimal point than there are zeros, then the number is rounded to the number of decimal places shown by the zeros. If there are more digits before the decimal point than zeros these will be displayed normally. |
# | Digit placeholder. This displays a digit or nothing. It works the same as the zero placeholder above, except that leading and trailing zeros are not displayed. For example 0.75 would be displayed using zero placeholders, but this would be .75 using # placeholders. |
. Decimal point. | Only one permitted per format string. This character depends on the settings in the Windows Control Panel. |
% | Percentage placeholder. Multiplies number by 100 and places % character where it appears in the format string |
, (comma) | Thousand separator. This is used if 0 or # placeholders are used and the format string contains a comma. One comma to the left of the decimal point indicates round to the nearest thousand. E.g. ##0, Two adjacent commas to the left of the thousand separator indicate rounding to the nearest million. E.g. ##0,, |
E- E+ | Scientific format. This displays the number exponentially. |
: (colon) | Time separator – used when formatting a time to split hours, minutes and seconds. |
/ | Date separator – this is used when specifying a format for a date |
– + £ $ ( ) | Displays a literal character. To display a character other than listed here, precede it with a backslash () |
User-Defined Formats for Dates and Times
These characters can all be used in you format string when formatting dates and times:
Character | Meaning |
c | Displays the date as ddddd and the time as ttttt |
d | Display the day as a number without leading zero |
dd | Display the day as a number with leading zero |
ddd | Display the day as an abbreviation (Sun – Sat) |
dddd | Display the full name of the day (Sunday – Saturday) |
ddddd | Display a date serial number as a complete date according to Short Date in the International settings of the windows Control Panel |
dddddd | Displays a date serial number as a complete date according to Long Date in the International settings of the Windows Control Panel. |
w | Displays the day of the week as a number (1 = Sunday) |
ww | Displays the week of the year as a number (1-53) |
m | Displays the month as a number without leading zero |
mm | Displays the month as a number with leading zeros |
mmm | Displays month as an abbreviation (Jan-Dec) |
mmmm | Displays the full name of the month (January – December) |
q | Displays the quarter of the year as a number (1-4) |
y | Displays the day of the year as a number (1-366) |
yy | Displays the year as a two-digit number |
yyyy | Displays the year as four-digit number |
h | Displays the hour as a number without leading zero |
hh | Displays the hour as a number with leading zero |
n | Displays the minute as a number without leading zero |
nn | Displays the minute as a number with leading zero |
s | Displays the second as a number without leading zero |
ss | Displays the second as a number with leading zero |
ttttt | Display a time serial number as a complete time. |
AM/PM | Use a 12-hour clock and display AM or PM to indicate before or after noon. |
am/pm | Use a 12-hour clock and use am or pm to indicate before or after noon |
A/P | Use a 12-hour clock and use A or P to indicate before or after noon |
a/p | Use a 12-hour clock and use a or p to indicate before or after noon |
I have columns of numbers that, for whatever reason, are formatted as text. This prevents me from using arithmetic functions such as the subtotal function. What is the best way to convert these «text numbers» to true numbers?
Here is a screenshot of the specific issue:
I’ve tried these snippets to no avail:
Columns(5).NumberFormat = "0"
and
Selection.PasteSpecial Paste:=xlPasteValues, Operation:=xlNone, SkipBlanks _
:=False, Transpose:=False
Teamothy
1,9903 gold badges15 silver badges24 bronze badges
asked Apr 21, 2016 at 13:41
aLearningLadyaLearningLady
1,9384 gold badges20 silver badges42 bronze badges
4
Use the below function (changing [E:E]
to the appropriate range for your needs) to circumvent this issue (or change to any other format such as «mm/dd/yyyy»):
[E:E].Select
With Selection
.NumberFormat = "General"
.Value = .Value
End With
P.S. In my experience, this VBA solution works SIGNIFICANTLY faster on large data sets and is less likely to crash Excel than using the ‘warning box’ method.
answered Apr 21, 2016 at 13:41
aLearningLadyaLearningLady
1,9384 gold badges20 silver badges42 bronze badges
3
I had this problem earlier and this was my solution.
With Worksheets("Sheet1").Columns(5)
.NumberFormat = "0"
.Value = .Value
End With
answered Apr 21, 2016 at 15:20
0
This can be used to find all the numeric values (even those formatted as text) in a sheet and convert them to single (CSng function).
For Each r In Sheets("Sheet1").UsedRange.SpecialCells(xlCellTypeConstants)
If IsNumeric(r) Then
r.Value = CSng(r.Value)
r.NumberFormat = "0.00"
End If
Next
answered Sep 2, 2017 at 21:29
JonesJones
1812 silver badges4 bronze badges
1
This converts all text in columns of an Excel Workbook to numbers.
Sub ConvertTextToNumbers()
Dim wBook As Workbook
Dim LastRow As Long, LastCol As Long
Dim Rangetemp As Range
'Enter here the path of your workbook
Set wBook = Workbooks.Open("yourWorkbook")
LastRow = Cells.Find(What:="*", After:=Range("A1"), SearchOrder:=xlByRows, SearchDirection:=xlPrevious).Row
LastCol = Cells.Find(What:="*", After:=Range("A1"), SearchOrder:=xlByColumns, SearchDirection:=xlPrevious).Column
For c = 1 To LastCol
Set Rangetemp = Cells(c).EntireColumn
Rangetemp.TextToColumns DataType:=xlDelimited, _
TextQualifier:=xlDoubleQuote, ConsecutiveDelimiter:=False, Tab:=True, _
Semicolon:=False, Comma:=False, Space:=False, Other:=False, FieldInfo _
:=Array(1, 1), TrailingMinusNumbers:=True
Next c
End Sub
answered Jan 11, 2017 at 15:39
1
''Convert text to Number with ZERO Digits and Number convert ZERO Digits
Sub ZERO_DIGIT()
On Error Resume Next
Dim rSelection As Range
Set rSelection = rSelection
rSelection.Select
With Selection
Selection.NumberFormat = "General"
.Value = .Value
End With
rSelection.Select
Selection.NumberFormat = "0"
Set rSelection = Nothing
End Sub
''Convert text to Number with TWO Digits and Number convert TWO Digits
Sub TWO_DIGIT()
On Error Resume Next
Dim rSelection As Range
Set rSelection = rSelection
rSelection.Select
With Selection
Selection.NumberFormat = "General"
.Value = .Value
End With
rSelection.Select
Selection.NumberFormat = "0.00"
Set rSelection = Nothing
End Sub
''Convert text to Number with SIX Digits and Number convert SIX Digits
Sub SIX_DIGIT()
On Error Resume Next
Dim rSelection As Range
Set rSelection = rSelection
rSelection.Select
With Selection
Selection.NumberFormat = "General"
.Value = .Value
End With
rSelection.Select
Selection.NumberFormat = "0.000000"
Set rSelection = Nothing
End Sub
answered Mar 14, 2020 at 9:10
0
The solution that for me works is:
For Each xCell In Selection
xCell.Value = CDec(xCell.Value)
Next xCell
answered Feb 22, 2018 at 17:56
Using aLearningLady’s answer above, you can make your selection range dynamic by looking for the last row with data in it instead of just selecting the entire column.
The below code worked for me.
Dim lastrow as Integer
lastrow = Cells(Rows.Count, 2).End(xlUp).Row
Range("C2:C" & lastrow).Select
With Selection
.NumberFormat = "General"
.Value = .Value
End With
answered Feb 10, 2019 at 18:18
MikeyMikey
701 gold badge1 silver badge10 bronze badges
The solution that worked for me many times is:
Sub ConvertTextToNumber()
With Range("A1:CX500") 'you can change the range
.NumberFormat = "General"
.Value = .Value
End With
End Sub
answered Sep 23, 2021 at 19:03
For large datasets a faster solution is required.
Making use of ‘Text to Columns’ functionality provides a fast solution.
Example based on column F, starting range at 25 to LastRow
Sub ConvTxt2Nr()
Dim SelectR As Range
Dim sht As Worksheet
Dim LastRow As Long
Set sht = ThisWorkbook.Sheets("DumpDB")
LastRow = sht.Cells(sht.Rows.Count, "F").End(xlUp).Row
Set SelectR = ThisWorkbook.Sheets("DumpDB").Range("F25:F" & LastRow)
SelectR.TextToColumns Destination:=Range("F25"), DataType:=xlDelimited, _
TextQualifier:=xlDoubleQuote, ConsecutiveDelimiter:=False, Tab:=True, _
Semicolon:=False, Comma:=False, Space:=False, Other:=False, FieldInfo _
:=Array(1, 1), TrailingMinusNumbers:=True
End Sub
answered Jan 15, 2019 at 7:07
LouisLouis
392 bronze badges
1
From the recorded macro one gets the code below; for a new application you just need to update selection and range:
Sub num()
Columns("B:B").Select
Selection.TextToColumns Destination:=Range("B1"), DataType:=xlDelimited, _
TextQualifier:=xlDoubleQuote, ConsecutiveDelimiter:=False, Tab:=True, _
Semicolon:=False, Comma:=False, Space:=False, Other:=False, FieldInfo _
:=Array(1, 1), TrailingMinusNumbers:=True
End Sub
L.Dutch
9263 gold badges17 silver badges38 bronze badges
answered Dec 14, 2022 at 14:59
I had problems making above codes work. To me multiplying with 1 did the trick:-)
Cells(1, 1).Select
Cells(1, 1) = ActiveCell * 1
answered Dec 23, 2021 at 12:13
Numeric values are defined by data types like integer or byte. These data types are used for optimizing the processing and memory allocation in Excel. In this guide, we’re going to show you how to convert string into number in Excel VBA.
Download Workbook
Data types in VBA
Like in some other programming languages, VBA uses data types to identify what variables it can store and how they are stored. Most of the data types in VBA define numeric values. Here is a brief list of numeric data types:
Data type | Storage | Range |
Byte | 1 byte | 0 to 255 |
Integer | 2 bytes | -32,768 to 32,767 |
Long | 4 bytes | -2,147,483,648 to 2,147,483,647 |
Single | 4 bytes | -3.402823E38 to -1.401298E-45 for negative values; 1.401298E-45 to 3.402823E38 for positive values |
Double | 8 bytes | -1.79769313486231E308 to-4.94065645841247E-324 for negative values; 4.94065645841247E-324 to 1.79769313486232E308 for positive values |
LongLong | 8 bytes |
-9,223,372,036,854,775,808 to 9,223,372,036,854,775,807 Valid on 64-bit platforms only. |
Currency | 8 bytes | -922,337,203,685,477.5808 to 922,337,203,685,477.5807 |
Decimal | 14 bytes | +/-79,228,162,514,264,337,593,543,950,335 with no decimal point; +/-7.9228162514264337593543950335 with 28 places to the right of the decimal |
Since there are many numeric data types, there are many functions to convert a string into number in Excel VBA.
Functions to a convert string into number in Excel VBA
All conversion functions use the same syntax: Each requires a single string argument to convert into a number. For example:
Each function returns an error If the string argument either is not a numeric or is outside the range of the data type being converted.
CInt(«A») returns a type mismatch error, because the «A» is not a numeric value.
CByte(«1250») returns an overflow exception.
Function | Return type | Example |
CByte | Byte | CByte(«65.75») returns 66 |
CCur | Currency | CCur(«$256,000.50») returns 256000.5 |
CDbl | Double | CDbl(128.239856 * 4.8 * 0.04) returns 24.622052352 |
CDec | Decimal | CDec(«15000000.5678») returns 15000000.5678 |
CInt | Integer | CInt(«1234.56») returns 1235 |
CLng | Long | CLng(«1,500,000.88») returns 15000001 |
CLngLng | LongLong | CLngLng(«1,250,500,000.88») returns 1250500001 |
CSng | Single | CSng(«5.67854») returns 5.67854 |
Bonus: Use IsNumeric function to verify value
To avoid type mismatch errors, you can use the IsNumeric function to check if the expression is numeric or not. The function returns Boolean value based on the expression. TRUE if the expression is numeric, FALSE otherwise.
Here is a sample function that can check the data first, and convert the it into an integer if it is numeric. If the argument is not a valid number, the function returns 0.
Function ConvertInt(arg As String) As Integer If IsNumeric(arg) Then ConvertInt = CInt(arg) End Function