Функции преобразования типов данных в 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 для того, чтобы указать, что результатом выполнения той или иной операции должны стать данные определенного типа, отличающегося от типа, заданного по умолчанию.
title | keywords | f1_keywords | ms.prod | ms.assetid | ms.date | ms.localizationpriority |
---|---|---|---|---|---|---|
Type conversion functions (VBA) |
vblr6.chm1008820 |
vblr6.chm1008820 |
office |
fd602e34-9de2-1e8b-46fe-6a2873d6a785 |
12/21/2018 |
high |
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. |
Remarks
If the expression passed to the function is outside the range of the data type being converted to, an error occurs.
[!NOTE]
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.
[!NOTE]
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.
Dim A, B, Check A = 5: B = 5 ' Initialize variables. Check = CBool(A = B) ' Check contains True. A = 0 ' Define variable. Check = CBool(A) ' Check contains False.
CByte function example
This example uses the CByte function to convert an expression to a Byte.
Dim MyDouble, MyByte MyDouble = 125.5678 ' MyDouble is a Double. MyByte = CByte(MyDouble) ' MyByte contains 126.
CCur function example
This example uses the CCur function to convert an expression to a Currency.
Dim MyDouble, MyCurr MyDouble = 543.214588 ' MyDouble is a Double. MyCurr = CCur(MyDouble * 2) ' Convert result of MyDouble * 2 ' (1086.429176) to a ' Currency (1086.4292).
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.
Dim MyDate, MyShortDate, MyTime, MyShortTime MyDate = "February 12, 1969" ' Define date. MyShortDate = CDate(MyDate) ' Convert to Date data type. MyTime = "4:35:47 PM" ' Define time. MyShortTime = CDate(MyTime) ' Convert to Date data type.
CDbl function example
This example uses the CDbl function to convert an expression to a Double.
Dim MyCurr, MyDouble MyCurr = CCur(234.456784) ' MyCurr is a Currency. MyDouble = CDbl(MyCurr * 8.2 * 0.01) ' Convert result to a Double.
CDec function example
This example uses the CDec function to convert a numeric value to a Decimal.
Dim MyDecimal, MyCurr MyCurr = 10000000.0587 ' MyCurr is a Currency. MyDecimal = CDec(MyCurr) ' MyDecimal is a Decimal.
CInt function example
This example uses the CInt function to convert a value to an Integer.
Dim MyDouble, MyInt MyDouble = 2345.5678 ' MyDouble is a Double. MyInt = CInt(MyDouble) ' MyInt contains 2346.
CLng function example
This example uses the CLng function to convert a value to a Long.
Dim MyVal1, MyVal2, MyLong1, MyLong2 MyVal1 = 25427.45: MyVal2 = 25427.55 ' MyVal1, MyVal2 are Doubles. MyLong1 = CLng(MyVal1) ' MyLong1 contains 25427. MyLong2 = CLng(MyVal2) ' MyLong2 contains 25428.
CSng function example
This example uses the CSng function to convert a value to a Single.
Dim MyDouble1, MyDouble2, MySingle1, MySingle2 ' MyDouble1, MyDouble2 are Doubles. MyDouble1 = 75.3421115: MyDouble2 = 75.3421555 MySingle1 = CSng(MyDouble1) ' MySingle1 contains 75.34211. MySingle2 = CSng(MyDouble2) ' MySingle2 contains 75.34216.
CStr function example
This example uses the CStr function to convert a numeric value to a String.
Dim MyDouble, MyString MyDouble = 437.324 ' MyDouble is a Double. MyString = CStr(MyDouble) ' MyString contains "437.324".
CVar function example
This example uses the CVar function to convert an expression to a Variant.
Dim MyInt, MyVar MyInt = 4534 ' MyInt is an Integer. MyVar = CVar(MyInt & 000) ' MyVar contains the string ' 4534000.
See also
- Data types summary
- Visual Basic Editor (VBE) Glossary
- Visual Basic conceptual topics
[!includeSupport and feedback]
title | keywords | f1_keywords | ms.prod | ms.assetid | ms.date | ms.localizationpriority |
---|---|---|---|---|---|---|
Type conversion functions (VBA) |
vblr6.chm1008820 |
vblr6.chm1008820 |
office |
fd602e34-9de2-1e8b-46fe-6a2873d6a785 |
12/21/2018 |
high |
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. |
Remarks
If the expression passed to the function is outside the range of the data type being converted to, an error occurs.
[!NOTE]
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.
[!NOTE]
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.
Dim A, B, Check A = 5: B = 5 ' Initialize variables. Check = CBool(A = B) ' Check contains True. A = 0 ' Define variable. Check = CBool(A) ' Check contains False.
CByte function example
This example uses the CByte function to convert an expression to a Byte.
Dim MyDouble, MyByte MyDouble = 125.5678 ' MyDouble is a Double. MyByte = CByte(MyDouble) ' MyByte contains 126.
CCur function example
This example uses the CCur function to convert an expression to a Currency.
Dim MyDouble, MyCurr MyDouble = 543.214588 ' MyDouble is a Double. MyCurr = CCur(MyDouble * 2) ' Convert result of MyDouble * 2 ' (1086.429176) to a ' Currency (1086.4292).
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.
Dim MyDate, MyShortDate, MyTime, MyShortTime MyDate = "February 12, 1969" ' Define date. MyShortDate = CDate(MyDate) ' Convert to Date data type. MyTime = "4:35:47 PM" ' Define time. MyShortTime = CDate(MyTime) ' Convert to Date data type.
CDbl function example
This example uses the CDbl function to convert an expression to a Double.
Dim MyCurr, MyDouble MyCurr = CCur(234.456784) ' MyCurr is a Currency. MyDouble = CDbl(MyCurr * 8.2 * 0.01) ' Convert result to a Double.
CDec function example
This example uses the CDec function to convert a numeric value to a Decimal.
Dim MyDecimal, MyCurr MyCurr = 10000000.0587 ' MyCurr is a Currency. MyDecimal = CDec(MyCurr) ' MyDecimal is a Decimal.
CInt function example
This example uses the CInt function to convert a value to an Integer.
Dim MyDouble, MyInt MyDouble = 2345.5678 ' MyDouble is a Double. MyInt = CInt(MyDouble) ' MyInt contains 2346.
CLng function example
This example uses the CLng function to convert a value to a Long.
Dim MyVal1, MyVal2, MyLong1, MyLong2 MyVal1 = 25427.45: MyVal2 = 25427.55 ' MyVal1, MyVal2 are Doubles. MyLong1 = CLng(MyVal1) ' MyLong1 contains 25427. MyLong2 = CLng(MyVal2) ' MyLong2 contains 25428.
CSng function example
This example uses the CSng function to convert a value to a Single.
Dim MyDouble1, MyDouble2, MySingle1, MySingle2 ' MyDouble1, MyDouble2 are Doubles. MyDouble1 = 75.3421115: MyDouble2 = 75.3421555 MySingle1 = CSng(MyDouble1) ' MySingle1 contains 75.34211. MySingle2 = CSng(MyDouble2) ' MySingle2 contains 75.34216.
CStr function example
This example uses the CStr function to convert a numeric value to a String.
Dim MyDouble, MyString MyDouble = 437.324 ' MyDouble is a Double. MyString = CStr(MyDouble) ' MyString contains "437.324".
CVar function example
This example uses the CVar function to convert an expression to a Variant.
Dim MyInt, MyVar MyInt = 4534 ' MyInt is an Integer. MyVar = CVar(MyInt & 000) ' MyVar contains the string ' 4534000.
See also
- Data types summary
- Visual Basic Editor (VBE) Glossary
- Visual Basic conceptual topics
[!includeSupport and feedback]
Преобразование типов данных
Для преобразования типов данных предназначены следующие функции:
CBool(<Значение>)
— преобразует число или строку в логический тип данных. Если преобразование невозможно возбуждается исключение. Пример:
Debug.Print CBool(0) ' Выведет: False
Debug.Print CBool(1) ' Выведет: True
Debug.Print CBool("True") ' Выведет: True
Debug.Print CBool("False") ' Выведет: False
CByte(<Значение>)
— преобразует значение в число типаByte
. Если преобразование невозможно возбуждается исключение. Пример:
Debug.Print CByte(0) ' Выведет: 0
Debug.Print CByte(145.8) ' Выведет: 146
Debug.Print CByte(145.3) ' Выведет: 145
Debug.Print CByte(145.5) ' Выведет: 146
CInt(<Значение>)
— преобразует значение в число типаInteger
. Если преобразование невозможно возбуждается исключение. Пример:
Debug.Print CInt("45") ' Выведет: 45
Debug.Print CInt(145.8) ' Выведет: 146
Debug.Print CInt(145.3) ' Выведет: 145
Debug.Print CInt(145.5) ' Выведет: 146
CLng(<Значение>)
— преобразует значение в число типаLong
. Если преобразование невозможно возбуждается исключение. Пример:
Debug.Print CLng("45,5") ' Выведет: 46
Debug.Print CLng(145.8) ' Выведет: 146
Debug.Print CLng(145.3) ' Выведет: 145
Debug.Print CLng(145.5) ' Выведет: 146
CSng(<Значение>)
— преобразует значение в число типаSingle
. Если преобразование невозможно возбуждается исключение. Пример:
Debug.Print CSng(145) ' Выведет: 145
Debug.Print CSng("45,5") ' Выведет: 45,5
CDbl(<Значение>)
— преобразует значение в число типаDouble
. Если преобразование невозможно возбуждается исключение. Пример:
Debug.Print CDbl(145) ' Выведет: 145
Debug.Print CDbl("45,5") ' Выведет: 45,5
CCur(<Значение>)
— преобразует значение в число типаCurrency
. Если преобразование невозможно возбуждается исключение. Пример:
Debug.Print CCur(145) ' Выведет: 145
Debug.Print CCur("45,5") ' Выведет: 45,5
CDec(<Значение>)
— преобразует значение в число типаDecimal
. Если преобразование невозможно возбуждается исключение. Пример:
Debug.Print CDec(145) ' Выведет: 145
Debug.Print CDec("45,5") ' Выведет: 45,5
CVar(<Значение>)
— преобразует значение в типVariant
. Пример:
Debug.Print TypeName(CVar(12)) ' Выведет: Integer
Debug.Print TypeName(CVar(12.5)) ' Выведет: Double
Debug.Print TypeName(CVar("Строка")) ' Выведет: String
CStr(<Значение>)
— преобразует значение в строку. Пример:
Debug.Print CStr(True) ' Выведет: True
Debug.Print "'" & CStr(145) & "'" ' Выведет: '145'
Debug.Print "'" & CStr(145.5) & "'" ' Выведет: '145,5'
Debug.Print "'" & CStr(-145.5) & "'" ' Выведет: '-145,5'
str(<Число>)
— преобразует число в строку. Первый символ в строке резервируется под знак числа. Если число является положительным, то первый символ будет пробелом, а если отрицательным — то первым символом будет знак минус. Обратите также внимание на то, что при выводе десятичный разделитель отображается в виде точки, а не в виде запятой, как это было при использовании функцииCStr()
. Пример:
Debug.Print "'" & str(145) & "'" ' Выведет: ' 145'
Debug.Print "'" & str(145.5) & "'" ' Выведет: ' 145.5'
Debug.Print "'" & str(-145.5) & "'" ' Выведет: '-145.5'
CDate(<Значение>)
— преобразует значение в типDate
. Если преобразование невозможно возбуждается исключение. Пример:
Debug.Print CDate("Декабрь 21, 2012") ' Выведет: 21.12.2012
В качестве примера рассмотрим возможность сложения двух чисел, введенных пользователем. Как вы уже знаете, вводить данные позволяет функция InputBox()
. Воспользуемся этой функцией для получения чисел от пользователя (листинг 2.4).
Dim x, y
x = InputBox("x = ") ' Вводим 5
y = InputBox("y = ") ' Вводим 12
Debug.Print x + y ' Выведет: 512
Результатом выполнения этого кода будет не число, а строка «512». Таким образом, следует запомнить, что функция InputBox()
возвращает результат в виде строки. Чтобы просуммировать два числа, необходимо преобразовать строку в число (листинг 2.5).
Dim x, y
x = CInt(InputBox("x = ")) ' Вводим 5
y = CInt(InputBox("y = ")) ' Вводим 12
Debug.Print x + y ' Выведет: 17
В этом случае мы получим число 17, как и должно быть. Однако если пользователь вместо числа введет строку, то программа завершится с фатальной ошибкой. Поэтому прежде чем преобразовывать значение в число необходимо проверить его на допустимость. Выполнить проверку возможности преобразования позволяют следующие функции:
IsNumeric(<Значение>)
— возвращает значениеTrue
, если значение можно преобразовать в число, иFalse
— в противном случае:
Debug.Print IsNumeric("10") ' Выведет: True
Debug.Print IsNumeric("10,5") ' Выведет: True
Debug.Print IsNumeric("10.5") ' Выведет: False
Debug.Print IsNumeric("Строка") ' Выведет: False
IsObject(<Переменная>)
— возвращает значениеTrue
, если переменная является объектной, иFalse
— в противном случае:
Dim obj As Object
Debug.Print IsObject(obj) ' Выведет: True
Set obj = Nothing
Debug.Print IsObject(obj) ' Выведет: True
Debug.Print IsObject("Строка") ' Выведет: False
IsEmpty(<Переменная>)
— возвращает значениеTrue
, если переменной не было присвоено значение, иFalse
— в противном случае:
Dim x
Debug.Print IsEmpty(x) ' Выведет: True
x = 10
Debug.Print IsEmpty(x) ' Выведет: False
x = Empty
Debug.Print IsEmpty(x) ' Выведет: True
IsNull(<Переменная>)
— возвращает значениеTrue
, если переменная содержит значениеNull
, иFalse
— в противном случае:
Dim x
Debug.Print IsNull(x) ' Выведет: False
x = Null
Debug.Print IsNull(x) ' Выведет: True
IsDate(<Значение>)
— возвращает значениеTrue
, если значение может быть преобразовано в типDate
, иFalse
— в противном случае:
Dim x
Debug.Print IsNull(x) ' Выведет: False
x = Null
Debug.Print IsNull(x) ' Выведет: True
Переделаем предыдущий пример (листинг 2.5) и используем функцию IsNumeric()
для проверки возможности преобразования введенного пользователем значения в число (листинг 2.6). Код оформим в виде процедуры с названием Сумма()
.
Sub Тест()
Dim x, y
x = InputBox("x = ") ' Вводим 5
If IsNumeric(x) = False Then
MsgBox "Ошибка. Вы ввели не число"
Exit Sub ' Завершаем выполнение процедуры
End If
y = InputBox("y = ") ' Вводим 12
If IsNumeric(y) = False Then
MsgBox "Ошибка. Вы ввели не число"
Exit Sub ' Завершаем выполнение процедуры
End If
MsgBox "Результат: " & CStr(CInt(x) + CInt(y)) ' Результат: 17
End Sub
Статьи по Visual Basic for Applications (VBA)
Return to VBA Code Examples
You may be required to convert numbers stored as text to actual numbers in your VBA code. In this tutorial, we are going to go over the functions that you need to use to convert a string to an integer, long, double, decimal or currency data type (Click here to learn about converting numbers to strings)
Convert String to Integer
You can use the CInt or CLng function to convert a string to an integer. If the fraction is less than .5 the function will round down, if the fraction is greater than or equal to .5 the function will round up. The following code will convert a string to an integer:
MsgBox CInt("7.55")
The result is:
The following code uses the CLng function to convert a string to an integer:
MsgBox CLng("13.5")
The result is:
Note: You can use the CInt or CLng function to convert a string to an integer or long (respectively) data types. The Long Data type is the same as an integer data type except larger numbers are allowed. In the past, the distinction was required because of memory constraints. In modern programming, there’s no reason not to use the long data type since memory is no longer an issue. So it’s always better to use a long data type instead of an integer.
You can use the Immediate Window to see how the value would be processed if not converted to an integer:
Debug.Print "13.5" + "13.5"
Usually, the text will be stored as a variable and this variable will need to be converted to a number data type as shown in the code below:
Sub Using_Variables()
Dim valueOne As String
valueOne = 5
MsgBox CLng(valueOne) + CLng(valueOne)
End Sub
Convert String to Decimal
You can use the CDbl or CDec function to convert a string to a decimal. The following code would convert a string to a double data type:
MsgBox CDbl("9.1819")
The result is:
The following code would convert a string to a decimal data type:
MsgBox CDec("13.57") + CDec("13.4")
The result is:
You can use the Immediate Window to see how the value would be processed if not converted to a double or decimal data type:
Debug.Print "13.57" + "13.4"
The result is:
Note: The decimal data type can store larger numbers than the double data type, so it’s always advisable to use the decimal data type when you are uncertain.
Convert String to Currency
You can use the CCur function to convert a string to a currency. The following code would convert a string to a currency data type:
Range("A1").Value = CCur("18.5")
The result is:
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!
Функции преобразования типов (Visual Basic)
Visual Studio 2013
Д ругие версии
Эти функции компилируются путем подстановки кода, т. е. код преобразования является частью кода, вычисляющего выражение. В некоторых случаях отсутствует вызов процедуры для выполнения преобразований, что повышает производительность. Каждая функция приводит выражение к определенному типу данных.
CBool(expression)
CByte(expression)
CChar(expression)
CDate(expression)
CDbl(expression)
CDec(expression)
CInt(expression)
CLng(expression)
CObj(expression)
CSByte(expression)
CShort(expression)
CSng(expression)
CStr(expression)
CUInt(expression)
CULng(expression)
CUShort(expression)
Часть
expression
Обязательный. Любое выражение исходного типа данных.
Тип данных возвращаемого значения.
Имя функции определяет возвращаемый тип, как показано в следующей таблице.
Пример
В следующем примере преобразуется переменная Object в Integer и String.
Public Sub objectConversion(ByVal anObject As Object)
Dim anInteger As Integer
Dim aString As String
anInteger = CType(anObject, Integer)
aString = CType(anObject, String)
End Sub
Имя функции |
Возвращаемый тип данных. |
Диапазон для аргумента expression |
CBool |
Тип данных Boolean (Visual Basic) |
Любое допустимое Char, String или числовое выражение. |
CByte |
Тип данных Byte (Visual Basic) |
от 0 до 255 (без знака); дробная часть округляется.1 |
CChar |
Тип данных Char (Visual Basic) |
Любое допустимое Char или String выражение; преобразуется только первый знак String; значение может быть от 0 до 65535 (без знака). |
CDate |
Тип данных Date (Visual Basic) |
Любое допустимое представление даты и времени. |
CDbl |
Тип данных Double (Visual Basic) |
от -1.79769313486231570E+308 до -4.94065645841246544E-324 для отрицательных значений; от 4.94065645841246544E-324 до 1.79769313486231570E+308 для положительных значений. |
CDec |
Тип данных Decimal (Visual Basic) |
+/-79228162514264337593543950335 для целых чисел, т.е. чисел без знаков после запятой. Для чисел с 28 десятичными разрядами диапазоном является +/-7.9228162514264337593543950335. Наименьшее возможное ненулевое число это 0.0000000000000000000000000001 (+/-1E-28). |
CInt |
Тип данных Integer (Visual Basic) |
от -2147483648 до 2147483647; дробная часть округляется.1 |
CLng |
Тип данных Long (Visual Basic) |
от -9,223,372,036,854,775,808 до 9,223,372,036,854,775,807; дробная часть округляется.1 |
CObj |
Тип данных Object |
Любое допустимое выражение. |
CSByte |
Тип данных SByte (Visual Basic) |
от -128 до 127; дробная часть округляется.1 |
CShort |
Тип данных Short (Visual Basic) |
от -32768 до 32767; дробная часть округляется.1 |
CSng |
Тип данных Single (Visual Basic) |
(От -3,402823E+38 до -1,401298E-45 для отрицательных значений; от 1,401298E-45 до 3,402823E+38 для положительных значений. |
CStr |
Тип данных String (Visual Basic) |
Возвращаемые значения функции CStr зависят от аргумента expression. Дополнительные сведения см. в разделе Возвращаемые значения функции CStr (Visual Basic) . |
CUInt |
Тип данных UInteger |
от 0 до 4,294,967,295 (без знака); дробная часть округляется.1 |
CULng |
Тип данных ULong (Visual Basic) |
от 0 до 18446744073709551615 (без знака); дробная часть округляется.1 |
CUShort |
Тип данных UShort (Visual Basic) |
от 0 до 65535 (без знака); дробная часть округляется.1 |
1 Дробные части могут быть подчиняться специальному типу округления под названием банковское округление. См. примечания для дополнительных сведений.
Заметки
Как правило предпочтительнее использовать функции преобразования типа Visual Basic, чем методы .NET Framework, например ToString() в классе Convert или в отдельном типе структуры или класса. Функции языка Visual Basic предназначены для оптимального взаимодействия с Visual Basic, и они также сделают исходный код короче и облегчат его чтение. Кроме того методы преобразования .NET Framework не всегда получают тот же результат, что функции Visual Basic, например при преобразовании Boolean к Integer. Дополнительные сведения см. в разделе Устранение неполадок, связанных с типами данных (Visual Basic) .
Поведение
- Приведение типа данных. В общем случае, функции преобразования типов данных можно использовать для приведения результата некоторой операции к определенному типу данных вместо типа данных, получаемого по умолчанию. Например, функция CDec используется для принудительного приведения результатов операций к десятичному типу в тех случаях, когда получаемые значения относятся к типу данных с одинарной точностью, двойной точностью или к целочисленному типу.
- Сбой преобразования. Если параметр expression, передаваемый в функцию, находится вне диапазона значений типа данных, в который преобразуется expression, возникает ошибка OverflowException .
- Дробная часть. При преобразовании нецелого значения к целочисленному типу функции преобразования целых чисел (CByte, CInt, CLng, CSByte, CShort, CUInt, CULng и CUShort) удаляют дробную часть и округляют значение до ближайшего целого числа.
- Преобразования даты/времени. Функция IsDate используется для определения возможности преобразования значения в дату и время. CDate распознает литералы даты и литералы времени, но не числовые значения. Чтобы преобразовать значение Date Visual Basic 6.0 к Date Visual Basic 2005 или более поздних версий, можно использовать метод DateTime.FromOADate .
- Нейтральные значения даты/времени. Тип данных Date (Visual Basic) всегда содержит и дату, и время. При преобразовании типов в Visual Basic нейтральным значением даты считается 1/1/1 (1 января 1 года), а нейтральным значением времени — 00:00:00 (полночь). Если значение с типом Date преобразуется в строку, функция CStr не включает нейтральные значения в конечную строку. Например, при преобразовании значения #January 1, 0001 9:30:00# в строку, будет возвращен результат «9:30:00»; дата отбрасывается. При этом сведения о дате останутся в исходном значении Date и могут быть извлечены с помощью таких функций, как DatePart .
- Учет языковых и региональных параметров. Функции преобразования типов, включающие строки, выполняют преобразования на основе текущих языковых и региональных параметров для приложения. Функция CDate распознает форматы даты согласно региональным параметрам системы. Необходимо предоставить день, месяц и год в правильном порядке для имеющихся региональных настроек, в противном случае дата может интерпретироваться неправильно. Полный формат даты не распознается, если он содержит строковое значение дня недели, например «Wednesday».
Если дробная часть равна точно 0,5, то функции преобразования целых чисел округлят его до ближайшего четного целого числа. Например, 0,5 округляется до 0, а 1,5 и 2,5 округляются до 2. Это иногда называется банковским округлением, и его целью является компенсация сдвигов, которые могут накапливаться при сложении многих таких чисел.
CInt и CLng отличаются от функций Int и Fix , которые вместо округления отсекают дробную часть числа. Кроме того Fix и Int всегда возвращают значение того же типа данных, что и переданное значение.
Если требуется преобразовать в или из строкового представление значения в формате, отличном от задаваемого языка, то невозможно использовать функции преобразования типа Visual Basic. Чтобы сделать это, используйте методы ToString(IFormatProvider) и Parse(String, IFormatProvider) для этих типов значений. Например, используйте Double.Parse при преобразовании строки к Double и используйте Double.ToString при преобразовании значения из типа Double в строку.
Функция CType
Ф ункция CType принимает второй аргумент typename и приводит expression к typename, где typename может быть любым типом данных, структурой, классом или интерфейсом, для которого существует допустимое преобразование.
Для сравнения CType с другими зарезервированными словами преобразования типов см. Оператор DirectCast (Visual Basic) и Оператор TryCast (Visual Basic) .
Пример использования функции CBool
В следующем примере для преобразования к Boolean используется функция CBool. Если результатом вычисления выражения является ненулевое значение, то CBool возвращает True; в противном случае она возвращает False.
VB
Dim a, b, c As Integer
Dim check As Boolean
a = 5
b = 5
‘ The following line of code sets check to True.
check = CBool(a = b)
c = 0
‘ The following line of code sets check to False.
check = CBool(c)
Пример использования функции CByte
В следующем примере для преобразования к Byte используется функция CByte.
VB
Dim aDouble As Double
Dim aByte As Byte
aDouble = 125.5678
‘ The following line of code sets aByte to 126.
aByte = CByte(aDouble)
Пример использования функции CChar
В следующем примере для преобразования первого символа выражения String к типу Char используется функция CChar.
VB
Dim aString As String
Dim aChar As Char
‘ CChar converts only the first character of the string.
aString = «BCD»
‘ The following line of code sets aChar to «B».
aChar = CChar(aString)
Входным аргументом CChar должен быть тип данных Char или String. Невозможно использовать функцию CChar для преобразования числа в символ, поскольку функция CChar не может принимать данные числовых типов. В этом примере получается число, представляющее кодовую позицию (код символа), которое преобразуется в соответствующий символ. Использует функцию InputBox для получения строки цифр, CInt для преобразования строки к типу Integer, а ChrW для преобразования строки к типу Char.
VB
Dim someDigits As String
Dim codePoint As Integer
Dim thisChar As Char
someDigits = InputBox(«Enter code point of character:»)
codePoint = CInt(someDigits)
‘ The following line of code sets thisChar to the Char value of codePoint.
thisChar = ChrW(codePoint)
Пример использования функции CDate
В следующем примере для преобразования строк к Date используется функция CDate. Как правило, не рекомендуется жестко кодировать дату и время в виде строк (как показано в этом примере). Вместо этого используйте литералы даты и времени, например #Feb 12, 1969# и #4:45:23 PM#.
VB
Dim aDateString, aTimeString As String
Dim aDate, aTime As Date
aDateString = «February 12, 1969»
aTimeString = «4:35:47 PM»
‘ The following line of code sets aDate to a Date value.
aDate = CDate(aDateString)
‘ The following line of code sets aTime to Date value.
aTime = CDate(aTimeString)
Пример использования алгоритма CDbl
VB
Dim aDec As Decimal
Dim aDbl As Double
‘ The following line of code uses the literal type character D to make aDec a Decimal.
aDec = 234.456784D
‘ The following line of code sets aDbl to 1.9225456288E+1.
aDbl = CDbl(aDec * 8.2D * 0.01D)
Пример использования функции CDec
В следующем примере для преобразования числа к Decimal используется функция CDec.
VB
Dim aDouble As Double
Dim aDecimal As Decimal
aDouble = 10000000.0587
‘ The following line of code sets aDecimal to 10000000.0587.
aDecimal = CDec(aDouble)
Пример использования функции CInt
В следующем примере для преобразования значения к Integer используется функция CInt.
VB
Dim aDbl As Double
Dim anInt As Integer
aDbl = 2345.5678
‘ The following line of code sets anInt to 2346.
anInt = CInt(aDbl)
Пример использования алгоритма CLng
В следующем примере для преобразования значения к Long используется функция CLng.
VB
Dim aDbl1, aDbl2 As Double
Dim aLng1, aLng2 As Long
aDbl1 = 25427.45
aDbl2 = 25427.55
‘ The following line of code sets aLng1 to 25427.
aLng1 = CLng(aDbl1)
‘ The following line of code sets aLng2 to 25428.
aLng2 = CLng(aDbl2)
Пример использования функции CObj
В следующем примере для преобразования числа к Object используется функция CObj. Переменная Object содержит только 4-байтовый указатель, указывающий на значение типа Double.
VB
Dim aDouble As Double
Dim anObject As Object
aDouble = 2.7182818284
‘ The following line of code sets anObject to a pointer to aDouble.
anObject = CObj(aDouble)
Пример использования функции CSByte
В следующем примере для преобразования числа к SByte используется функция CSByte.
VB
Dim aDouble As Double
Dim anSByte As SByte
aDouble = 39.501
‘ The following line of code sets anSByte to 40.
anSByte = CSByte(aDouble)
Пример использования функции CShort
В следующем примере для преобразования числа к Short используется функция CShort.
VB
Dim aByte As Byte
Dim aShort As Short
aByte = 100
‘ The following line of code sets aShort to 100.
aShort = CShort(aByte)
Пример использования алгоритма CSng
В следующем примере для преобразования значения к Single используется функция CSng.
VB
Dim aDouble1, aDouble2 As Double
Dim aSingle1, aSingle2 As Single
aDouble1 = 75.3421105
aDouble2 = 75.3421567
‘ The following line of code sets aSingle1 to 75.34211.
aSingle1 = CSng(aDouble1)
‘ The following line of code sets aSingle2 to 75.34216.
aSingle2 = CSng(aDouble2)
Пример использования алгоритма CStr
В следующем примере для преобразования числа к String используется функция CStr.
VB
Dim aDouble As Double
Dim aString As String
aDouble = 437.324
‘ The following line of code sets aString to «437.324».
aString = CStr(aDouble)
В следующем примере для преобразования Date к String используется функция CStr.
VB
Dim aDate As Date
Dim aString As String
‘ The following line of code generates a COMPILER ERROR because of invalid format.
‘ aDate = #February 12, 1969 00:00:00#
‘ Date literals must be in the format #m/d/yyyy# or they are invalid.
‘ The following line of code sets the time component of aDate to midnight.
aDate = #2/12/1969#
‘ The following conversion suppresses the neutral time value of 00:00:00.
‘ The following line of code sets aString to «2/12/1969».
aString = CStr(aDate)
‘ The following line of code sets the time component of aDate to one second past midnight.
aDate = #2/12/1969 12:00:01 AM#
‘ The time component becomes part of the converted value.
‘ The following line of code sets aString to «2/12/1969 12:00:01 AM».
aString = CStr(aDate)
Функция CStr всегда предоставляет значение с типом Date в стандартном кратком формате для текущих региональных параметров, например 6/15/2003 4:35:47 PM. Однако CStr подавляет нейтральные значения 1/1/0001 для даты и 00:00:00 для времени.
Более подробно сведения о значениях, возвращаемых CStr, содержатся в разделе Возвращаемые значения функции CStr (Visual Basic) .
Пример использования функции CUInt
В следующем примере для преобразования числа к UInteger используется функция CUInt.
VB
Dim aDouble As Double
Dim aUInteger As UInteger
aDouble = 39.501
‘ The following line of code sets aUInteger to 40.
aUInteger = CUInt(aDouble)
Пример использования функции CULng
В следующем примере для преобразования числа к ULong используется функция CULng.
VB
Dim aDouble As Double
Dim aULong As ULong
aDouble = 39.501
‘ The following line of code sets aULong to 40.
aULong = CULng(aDouble)
Пример использования функции CShort
В следующем примере для преобразования числа к UShort используется функция CUShort.
VB
Dim aDouble As Double
Dim aUShort As UShort
aDouble = 39.501
‘ The following line of code sets aUShort to 40.
aUShort = CUShort(aDouble)
См. также
Ссылки
Функции преобразования (Visual Basic)
Asc
AscW
Chr
ChrW
Int
Fix
Format
Hex
Oct
Str
Val
Другие ресурсы
Преобразование типов в Visual Basic
In this article I will explain how you can convert data types to one another.
Jump To :
- String Conversions
- Convert String to a Numeric Data Type
- Check if String is Numeric, IsNumeric()
- Convert String to Integer, CInt()
- Convert String to Double, CDbl()
- Convert String to Long, CLng()
- Convert String to Single, CSng()
- Convert String to Decimal, CDec()
- Convert String to Date
- Check if String is a Date, IsDate()
- Convert a String to a Date, CDate()
- Convert String to a Numeric Data Type
- Numeric Conversions
- Converting a Numeric Value to a String, Str()
- Converting a Numeric Value to Another Numeric Data type
- Converting a Numeric Value to a Date, CDate()
- Date Conversions
- Converting a Date to a String, Str()
- Converting a Date to a Numeric Data type
- Examples
String Conversions:
Convert String to a Numeric Data Type:
There may several situations where you might end up with a string variable that needs to be converted to a numeric data type:
Situation 1: You are using a textbox for getting data from the user. The Textbox.Text property will return a string data type. If you are going to be doing arithmetic operations on the value in the textbox then you are going to have to convert it to a numeric value.
Situation 2: There are numbers among a string input (i.e “1094-wellington St.”) and after extracting the numeric parts you want to to arithmetic operations on them.
Situation 3: The worksheet cells are in the Text format. You copy all the cells to an array. The array might store the numbers in text format. In order to be able to do arithmetic operations on the numeric values you would need to convert the strings to numbers.
Check if String is Numeric, IsNumeric():
IsNumeric() checks if the input string is a numeric value. It would be a good idea to check if the string you are working with is actually a numeric value before trying to convert it. If the string is not numeric and you try to convert it to a numeric value an exception will be thrown. The code below checks if the string strTemp is numeric or not:
If IsNumeric(strTemp) Then
'strTemp is a numeric value
Else
'strTemp is not a numeric value
End If
Convert String to Integer, CInt():
The following code converts the string “34” to an integer:
Sub Example1()
Dim strInteger As String
Dim intInteger As Integer
strInteger = "34"
intInteger = CInt(strInteger)
End Sub
Convert String to Double, CDbl():
The following code converts the string “34.5” to a double:
Sub Example2()
Dim strDouble As String
Dim dblValue As Double
strDouble = "34.5"
dblValue = CDbl(strDouble)
End Sub
Convert String to Long, CLng():
The following code converts the string “34” to a Long:
Sub Example3()
Dim strLong As String
Dim lngValue As Long
strLong = "34"
lngValue= CLng(strLong )
End Sub
Convert String to Single, CSng():
The following code converts the string “34.5” to a Single:
Sub Example4()
Dim strSingle As String
Dim sngValue As Single
strSingle = "34.5"
sngValue= CSng(strSingle )
End Sub
Convert String to Decimal, CDec():
The following code converts the string “34.54” to a Decimal:
Sub Example5()
Dim strDecimal As String
Dim decValue As Variant
strDecimal = "34.5"
decValue= CDec(strDecimal )
End Sub
Note: Decimal data types can’t be declared directly.
Convert String to Date:
Check if String is a Date, IsDate():
The code below checks if the string strDate is a Date:
If IsDate(strDate) Then
'strDate is a Date
Else
'strDate is not a Date
End If
Convert a String to a Date, CDate():
The following code converts the string “1/1/2004” to a Date:
Sub Example6()
Dim strDate As String
Dim dateValue As Date
strDate = "1/1/2004"
dateValue = CDate(strDate)
End Sub
Numeric Conversions:
Converting a Numeric Value to a String, Str():
There are many situations where you would need to convert a number to a string, below are just a few examples:
Situation 1: Trying to loop through ranges using the “A1:B1” notation. See Referencing Ranges In Excel Using VBA for more information.
Situation 2: When concatenating a numeric value to a string. See VBA Excel String Processing and Manipulation for more information.
All numeric value can be converted to a string using the Str() function:
Sub Example6()
Dim intValue As Integer
Dim dblValue As Double
Dim lngValue As Long
Dim sngValue As Single
Dim decValue As Variant
Dim strTemp As String
intValue = 1
dblValue = 34.5
lngValue = 1
sngValue = 34.5
'decimal values can't be declared directly
decValue = CDec(45.54)
strTemp = Str(intValue)
strTemp = Str(dblValue)
strTemp = Str(lngValue)
strTemp = Str(sngValue)
strTemp = Str(decValue)
End Sub
Converting a Numeric Value to Another Numeric Data Type:
Numeric values are implicitly converted to the appropriate data type in assignments. In the example below, when assigning the double value to the integer variable, the number 34.5 is implicitly converted to the equivalent integer during the assignment:
Sub Example7()
Dim intValue As Integer
Dim dblValue As Double
dblValue = 34.5
intValue = dblValue
End Sub
Although you could always use the explicit conversion functions:
CInt(expression): Converts the input expression to an integer.
CDbl(expression): Converts the input expression to a double.
CLng(expression): Converts the input expression to a long.
CSng(expression): Converts the input expression to a single.
CDec(expression): Converts the input expression to a decimal.
Converting a Numeric Value to a Date, CDate():
Numbers can be converted to dates and vice versa. You can see some examples below:
Conversions from a numeric value to a date can be done through the function CDate():
Sub example8()
Dim intDate As Integer
Dim objDate As Date
intDate = 1
objDate = CDate(intDate)
End Sub
Date Conversions:
Converting a Date Value to a String, Str():
Dates can be converted to a string using the function Str():
Sub example9()
Dim strDate As String
strDate = Str(Now)
End Sub
Converting a Date Value to a Numeric Data type:
Dates can be converted to and from numeric data types. You can see some examples below:
Although you can convert integers to dates, but it can’t be done vice versa. Dates can only be converted to double and single data type:
Sub example10()
Dim dblDate As Double
Dim sngDate As Single
dblDate = CDbl(Date)
sngDate = CSng(Now)
End Sub
Now let us look at a few more practical examples where conversion is required.
Example 1: String to Integer conversion
Say you have a column in a table that lists the amount in various currencies and you want to find the sum of amounts of one particular currency in your VBA code. Here the cell values have the currency code pre-fixed and hence, will be treated as strings. So, conversion will be required to calculate the sum.
Here is how the code will look like if you want to sum the USD amount.
First, we use the in-string function (InStr) to check whether the currency type is what we need. If so, we remove the currency code (first four characters) from the string using the Right function. Now we are left with only the amount, but in a string format and obviously we cannot perform the addition on it.
So, we use data type conversion by using the function: CDbl and finally we sum it up.
Sub changeDataType() Dim amount As Double Dim strVal As String Dim i As Integer, lastRow As Integer Dim dataRange As Range lastRow = Sheet1.UsedRange.Rows.Count Set dataRange = Sheet1.Range("A2:A" &amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp; lastRow) For i = 1 To dataRange.Rows.Count If InStr(1, dataRange.Cells(i, 1), "USD") = 1 Then Debug.Print dataRange.Cells(i, 1) strVal = Right(dataRange.Cells(i, 1), Len(dataRange.Cells(i, 1)) - 4) amount = amount + CDbl(strVal) End If Next i MsgBox amount End SubThe amount can be then used further in your code. The output of this program will be:
You can also define this as a function with the currency type as an input argument. In this way, whenever you call the function, you can specify the currency, thus making it dynamic.
Example 2: Decimal to Hex conversion
Though this is not data type conversion, it is worth mentioning how to convert decimal numbers to hex and vice-versa.
So, for decimal to hex conversion, we use the function Dec2Hex as illustrated below
Sub decToHex() Dim decVal As String, hexVal As String decVal = "9999" hexVal = Application.WorksheetFunction.Dec2Hex(DecVal) MsgBox hexVal End SubAnd here is the output
Example 3: Hex to Decimal conversion
Similar to the above example, let’s have a look at hex to decimal conversion.
So, for hex to decimal conversion, we will use the function Hex2Dec as illustrated belowSub hexToDec() Dim decVal As String, hexVal As String hexVal = "270F" decVal = Application.WorksheetFunction.Hex2Dec(hexVal) MsgBox decVal End SubAnd the output will be
See Also:
- Referencing Ranges In Excel Using VBA
- Excel VBA, Working with Dates, Comparing, Adding, Subtracting …
- VBA Excel String Processing and Manipulation
If you need assistance with your code, or you are looking to hire a VBA programmer feel free to contact me. Also please visit my website www.software-solutions-online.com