Vba excel приведение типов

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

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

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

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

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

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

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

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

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

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

Функция CBool

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

Dim a

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

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

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

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

Dim a, b, c

a = «Test1»

b = «Test2»

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

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

Функция CByte

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

Dim a, b, c

a = 654

b = 3.36

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

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

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

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

Функция CCur

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

Dim a, b, c

a = 254.6598254

b = 569.2156843

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

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

Функция CDate

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

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

a = «28.01.2021»

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

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

Dim a

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

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

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

Функция CDbl

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

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

a = «45,3695423»

b = «548955,756»

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

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

Функция CDec

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

Dim a As String, b As Double, c

a = «5,9228162514264337593543950335»

b = 5.92281625142643

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

Dim a As Double, b As String, c

a = 4.2643E14

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

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

Функция CInt

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

Dim a As String, b As Integer

a = «2355,9228»

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

Функция CLng

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

Dim a As Date, b As Long

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

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

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

Функция CSng

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

Dim a As String, b As Single

a = «3,2365625106»

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

Функция CStr

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

Dim a As Single, b As String

a = 5106.23

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

Функция CVar

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

Dim a As Double, b As String, c

a = 549258.232546

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

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

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

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


VBA Data Type Conversion Functions in Excel can be use to convert numeric values or strings to another specified format. These are CBool,CByte, CCur, CDate, CDbl, CDec, CInt, CLng, CSng, CStr, CVar etc. These functions are Built-In functions. We can use these VBA data type conversion functions in either procedure or function. These functions we use in the VBA editor window in Excel. These data type conversion functions you can use any number of times in VBA macro codes. We can use these multiple data type conversion functions in one statement.

Here are the list of Data Type Conversion functions. And also find its syntax and return type.

Function Description Syntax Return Type
VBA CBool VBA CBool function converts an expression to a Boolean data type. CBool(Expression) Boolean
VBA CByte VBA CByte function converts an expression to a Byte data type. CByte(Expression) Byte
VBA CCur VBA CCur function converts an expression to a Currency data type. CCur(Expression) Currency
VBA CDate VBA CDate function converts an expression to a Date data type. CDate(Expression) Date
VBA CDbl VBA CDbl function converts an expression to a Double data type. CDbl(Expression) Double
VBA CDec VBA CDec function converts an expression to a Decimal data subtype. CDec(Expression) Decimal
VBA CInt VBA CInt function converts an expression to an Integer data type. CInt(Expression) Integer
VBA CLng VBA CLng function converts an expression to a Long data type. CLng(Expression) Long
VBA CSng VBA CSng function converts an expression to a Single data type. CSng(Expression) Single
VBA CStr VBA CStr function converts an expression to a String data type. CStr(Expression) String
VBA CVar VBA CVar function converts an expression to a Variant data type. CVar(Expression) Variant

Other Useful Resources:

Click on the following links of the useful resources. These helps to learn and gain more knowledge.

VBA Tutorial VBA Functions List VBA Arrays in Excel Blog

VBA Editor Keyboard Shortcut Keys List VBA Interview Questions & Answers

Содержание

  1. Type Conversion Functions (Visual Basic)
  2. Syntax
  3. Return Value Data Type
  4. Remarks
  5. Behavior
  6. CType Function
  7. CBool Example
  8. CByte Example
  9. CChar Example
  10. CDate Example
  11. CDbl Example
  12. CDec Example
  13. CInt Example
  14. CLng Example
  15. CObj Example
  16. CSByte Example
  17. CShort Example
  18. CSng Example
  19. CStr Example
  20. CUInt Example
  21. CULng Example
  22. CUShort Example
  23. Функции преобразования типов (Visual Basic)
  24. Синтаксис
  25. Часть
  26. Тип данных возвращаемого значения
  27. Remarks
  28. Поведение
  29. CType Function
  30. Пример CBool
  31. Пример CByte
  32. Пример CChar
  33. Пример CDate
  34. Пример CDbl
  35. Пример CDec
  36. Пример CInt
  37. Пример CLng
  38. Пример CObj
  39. Пример CSByte
  40. Пример CShort
  41. Пример CSng
  42. Пример CStr
  43. Пример CUInt
  44. Пример CULng
  45. Пример CUShort

Type Conversion Functions (Visual Basic)

These functions are compiled inline, meaning the conversion code is part of the code that evaluates the expression. Sometimes there is no call to a procedure to accomplish the conversion, which improves performance. Each function coerces an expression to a specific data type.

Syntax

expression
Required. Any expression of the source data type.

Return Value Data Type

The function name determines the data type of the value it returns, as shown in the following table.

Function name Return data type Range for expression argument
CBool Boolean Data Type Any valid Char or String or numeric expression.
CByte Byte Data Type Byte.MinValue (0) through Byte.MaxValue (255) (unsigned); fractional parts are rounded. 1

Starting with Visual Basic 15.8, Visual Basic optimizes the performance of floating-point to byte conversion with the CByte function; see the Remarks section for more information. See the CInt Example section for an example.

CChar Char Data Type Any valid Char or String expression; only first character of a String is converted; value can be 0 through 65535 (unsigned).
CDate Date Data Type Any valid representation of a date and time.
CDbl Double Data Type -1.79769313486231570E+308 through -4.94065645841246544E-324 for negative values; 4.94065645841246544E-324 through 1.79769313486231570E+308 for positive values.
CDec Decimal Data Type +/-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 (+/-1E-28).
CInt Integer Data Type Int32.MinValue (-2,147,483,648) through Int32.MaxValue (2,147,483,647); fractional parts are rounded. 1

Starting with Visual Basic 15.8, Visual Basic optimizes the performance of floating-point to integer conversion with the CInt function; see the Remarks section for more information. See the CInt Example section for an example.

CLng Long Data Type Int64.MinValue (-9,223,372,036,854,775,808) through Int64.MaxValue (9,223,372,036,854,775,807); fractional parts are rounded. 1

Starting with Visual Basic 15.8, Visual Basic optimizes the performance of floating-point to 64-bit integer conversion with the CLng function; see the Remarks section for more information. See the CInt Example section for an example.

CObj Object Data Type Any valid expression.
CSByte SByte Data Type SByte.MinValue (-128) through SByte.MaxValue (127); fractional parts are rounded. 1

Starting with Visual Basic 15.8, Visual Basic optimizes the performance of floating-point to signed byte conversion with the CSByte function; see the Remarks section for more information. See the CInt Example section for an example.

CShort Short Data Type Int16.MinValue (-32,768) through Int16.MaxValue (32,767); fractional parts are rounded. 1

Starting with Visual Basic 15.8, Visual Basic optimizes the performance of floating-point to 16-bit integer conversion with the CShort function; see the Remarks section for more information. See the CInt Example section for an example.

CSng Single Data Type -3.402823E+38 through -1.401298E-45 for negative values; 1.401298E-45 through 3.402823E+38 for positive values.
CStr String Data Type Returns for CStr depend on the expression argument. See Return Values for the CStr Function.
CUInt UInteger Data Type UInt32.MinValue (0) through UInt32.MaxValue (4,294,967,295) (unsigned); fractional parts are rounded. 1

Starting with Visual Basic 15.8, Visual Basic optimizes the performance of floating-point to unsigned integer conversion with the CUInt function; see the Remarks section for more information. See the CInt Example section for an example.

CULng ULong Data Type UInt64.MinValue (0) through UInt64.MaxValue (18,446,744,073,709,551,615) (unsigned); fractional parts are rounded. 1

Starting with Visual Basic 15.8, Visual Basic optimizes the performance of floating-point to unsigned long integer conversion with the CULng function; see the Remarks section for more information. See the CInt Example section for an example.

CUShort UShort Data Type UInt16.MinValue (0) through UInt16.MaxValue (65,535) (unsigned); fractional parts are rounded. 1

Starting with Visual Basic 15.8, Visual Basic optimizes the performance of floating-point to unsigned 16-bit integer conversion with the CUShort function; see the Remarks section for more information. See the CInt Example section for an example.

1 Fractional parts can be subject to a special type of rounding called banker’s rounding. See «Remarks» for more information.

As a rule, you should use the Visual Basic type conversion functions in preference to the .NET Framework methods such as ToString() , either on the Convert class or on an individual type structure or class. The Visual Basic functions are designed for optimal interaction with Visual Basic code, and they also make your source code shorter and easier to read. In addition, the .NET Framework conversion methods do not always produce the same results as the Visual Basic functions, for example when converting Boolean to Integer . For more information, see Troubleshooting Data Types.

Starting with Visual Basic 15.8, the performance of floating-point-to-integer conversion is optimized when you pass the Single or Double value returned by the following methods to one of the integer conversion functions ( CByte , CShort , CInt , CLng , CSByte , CUShort , CUInt , CULng ):

This optimization allows code that does a large number of integer conversions to run up to twice as fast. The following example illustrates these optimized floating-point-to-integer conversions:

Behavior

Coercion. In general, you can use the data type conversion functions to coerce the result of an operation to a particular data type rather than the default data type. For example, use CDec to force decimal arithmetic in cases where single-precision, double-precision, or integer arithmetic would normally take place.

Failed Conversions. If the expression passed to the function is outside the range of the data type to which it is to be converted, an OverflowException occurs.

Fractional Parts. When you convert a nonintegral value to an integral type, the integer conversion functions ( CByte , CInt , CLng , CSByte , CShort , CUInt , CULng , and CUShort ) remove the fractional part and round the value to the closest integer.

If the fractional part is exactly 0.5, the integer conversion functions round it to the nearest even integer. For example, 0.5 rounds to 0, and 1.5 and 2.5 both round to 2. This is sometimes called banker’s rounding, and its purpose is to compensate for a bias that could accumulate when adding many such numbers together.

CInt and CLng differ from the Int and Fix functions, which truncate, rather than round, the fractional part of a number. Also, Fix and Int always return a value of the same data type as you pass in.

Date/Time Conversions. Use the IsDate function to determine if a value can be converted to a date and time. CDate recognizes date literals and time literals but not numeric values. To convert a Visual Basic 6.0 Date value to a Date value in Visual Basic 2005 or later versions, you can use the DateTime.FromOADate method.

Neutral Date/Time Values. The Date Data Type always contains both date and time information. For purposes of type conversion, Visual Basic considers 1/1/0001 (January 1 of the year 1) to be a neutral value for the date, and 00:00:00 (midnight) to be a neutral value for the time. If you convert a Date value to a string, CStr does not include neutral values in the resulting string. For example, if you convert #January 1, 0001 9:30:00# to a string, the result is «9:30:00 AM»; the date information is suppressed. However, the date information is still present in the original Date value and can be recovered with functions such as DatePart function.

Culture Sensitivity. The type conversion functions involving strings perform conversions based on the current culture settings for the application. For example, CDate recognizes date formats according to the locale setting of your system. You must provide the day, month, and year in the correct order for your locale, or the date might not be interpreted correctly. A long date format is not recognized if it contains a day-of-the-week string, such as «Wednesday».

If you need to convert to or from a string representation of a value in a format other than the one specified by your locale, you cannot use the Visual Basic type conversion functions. To do this, use the ToString(IFormatProvider) and Parse(String, IFormatProvider) methods of that value’s type. For example, use Double.Parse when converting a string to a Double , and use Double.ToString when converting a value of type Double to a string.

CType Function

The CType Function takes a second argument, typename , and coerces expression to typename , where typename can be any data type, structure, class, or interface to which there exists a valid conversion.

For a comparison of CType with the other type conversion keywords, see DirectCast Operator and TryCast Operator.

CBool Example

The following example uses the CBool function to convert expressions to Boolean values. If an expression evaluates to a nonzero value, CBool returns True ; otherwise, it returns False .

CByte Example

The following example uses the CByte function to convert an expression to a Byte .

CChar Example

The following example uses the CChar function to convert the first character of a String expression to a Char type.

The input argument to CChar must be of data type Char or String . You cannot use CChar to convert a number to a character, because CChar cannot accept a numeric data type. The following example obtains a number representing a code point (character code) and converts it to the corresponding character. It uses the InputBox function to obtain the string of digits, CInt to convert the string to type Integer , and ChrW to convert the number to type Char .

CDate Example

The following example uses the CDate function to convert strings to Date values. 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 #Feb 12, 1969# and #4:45:23 PM#, instead.

CDbl Example

CDec Example

The following example uses the CDec function to convert a numeric value to Decimal .

CInt Example

The following example uses the CInt function to convert a value to Integer .

CLng Example

The following example uses the CLng function to convert values to Long .

CObj Example

The following example uses the CObj function to convert a numeric value to Object . The Object variable itself contains only a four-byte pointer, which points to the Double value assigned to it.

CSByte Example

The following example uses the CSByte function to convert a numeric value to SByte .

CShort Example

The following example uses the CShort function to convert a numeric value to Short .

CSng Example

The following example uses the CSng function to convert values to Single .

CStr Example

The following example uses the CStr function to convert a numeric value to String .

The following example uses the CStr function to convert Date values to String values.

CStr always renders a Date value in the standard short format for the current locale, for example, «6/15/2003 4:35:47 PM». However, CStr suppresses the neutral values of 1/1/0001 for the date and 00:00:00 for the time.

For more detail on the values returned by CStr , see Return Values for the CStr Function.

CUInt Example

The following example uses the CUInt function to convert a numeric value to UInteger .

CULng Example

The following example uses the CULng function to convert a numeric value to ULong .

CUShort Example

The following example uses the CUShort function to convert a numeric value to UShort .

Источник

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

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

Синтаксис

Часть

expression
Обязательный. Любое выражение исходного типа данных.

Тип данных возвращаемого значения

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

Имя функции Тип возвращаемых данных Диапазон для expression аргумента
CBool Логический тип данных Любое допустимое Char или String числовое выражение.
CByte Тип данных Byte Byte.MinValue (0) до Byte.MaxValue (255) (без знака); дробные части округляются. 1

Начиная с Visual Basic 15.8, Visual Basic оптимизирует производительность преобразования с плавающей запятой в байт с помощью функции. Дополнительные сведения см. в CByte разделе «Примечания». Пример см. в разделе » Пример CInt «.

CChar Тип данных Char Любое допустимое Char или String выражение; преобразуется только первый символ String ; значение может составлять от 0 до 65535 (без знака).
CDate Тип данных Date Любое допустимое представление даты и времени.
CDbl Тип данных Double -1.79769313486231570E+308–-4.94065645841246544E-324 для отрицательных значений; 4.94065645841246544E-324–1.79769313486231570E+308 для положительных значений.
CDec Тип данных Decimal +/-79,228,162,514,264,337,593,543,950,335 для нулевые числа, то есть числа без десятичных разрядов. Для чисел с 28 десятичными разрядами диапазон — +/-7.9228162514264337593543943950335. Наименьшее возможное ненулевое число — 0,00000000000000000000000001 (+/-1E-28).
CInt Целочисленный тип данных Int32.MinValue (-2 147 483 648) до Int32.MaxValue (2 147 483 647); дробные части округляются. 1

Начиная с Visual Basic 15.8, Visual Basic оптимизирует производительность преобразования с плавающей запятой в целочисленное с помощью функции. Дополнительные сведения см. в CInt разделе «Примечания». Пример см. в разделе » Пример CInt «.

CLng Тип данных Long Int64.MinValue (-9 223 372 036 854 775 808) до Int64.MaxValue (9 223 372 036 854 775 807); дробные части округляются. 1

Начиная с Visual Basic 15.8, Visual Basic оптимизирует производительность преобразования с плавающей запятой до 64-разрядного целого числа с помощью функции. Дополнительные сведения см. в CLng разделе «Примечания». Пример см. в разделе » Пример CInt «.

CObj Object Data Type Любое допустимое выражение.
CSByte Тип данных SByte SByte.MinValue (–128) до SByte.MaxValue (127); дробные части округляются. 1

Начиная с Visual Basic 15.8, Visual Basic оптимизирует производительность преобразования с плавающей запятой на подписанный байт с помощью функции. Дополнительные сведения см. в CSByte разделе «Примечания». Пример см. в разделе » Пример CInt «.

CShort Тип данных Short Int16.MinValue (-32 768) до Int16.MaxValue (32 767); дробные части округляются. 1

Начиная с Visual Basic 15.8, Visual Basic оптимизирует производительность преобразования с плавающей запятой до 16-разрядного целого числа с помощью функции. Дополнительные сведения см. в CShort разделе «Примечания». Пример см. в разделе » Пример CInt «.

CSng Тип данных Single -3.402823E+38–-1.401298E-45 для отрицательных значений; От 1.401298E-45 до 3.402823E+38 для положительных значений.
CStr Тип строковых данных Возвращает значение для CStr зависимости от аргумента expression . См. возвращаемые значения для функции CStr.
CUInt Тип данных UInteger UInt32.MinValue (0) до UInt32.MaxValue (4 294 967 295) (без знака); дробные части округляются. 1

Начиная с Visual Basic 15.8, Visual Basic оптимизирует производительность преобразования с плавающей запятой до целого числа без знака с помощью функции. Дополнительные сведения см. в CUInt разделе «Примечания». Пример см. в разделе » Пример CInt «.

CULng Тип данных ULong UInt64.MinValue (0) до UInt64.MaxValue (18 446 744 073 709 551 615) (без знака); дробные части округляются. 1

Начиная с Visual Basic 15.8, Visual Basic оптимизирует производительность преобразования с плавающей запятой до целого числа без знака с помощью функции. Дополнительные сведения см. в CULng разделе «Примечания». Пример см. в разделе » Пример CInt «.

CUShort Тип данных UShort UInt16.MinValue (0) до UInt16.MaxValue (65 535) (без знака); дробные части округляются. 1

Начиная с Visual Basic 15.8, Visual Basic оптимизирует производительность с плавающей запятой до 16-разрядного преобразования целых чисел без знака с помощью функции; дополнительные сведения см. в CUShort разделе «Примечания». Пример см. в разделе » Пример CInt «.

1 Дробные части могут быть подвержены особому типу округления, называемого округлением банкира. Дополнительные сведения см. в разделе «Примечания».

Как правило, следует использовать функции преобразования типов Visual Basic в предпочтениях методов платформа .NET Framework, таких как ToString() Convert класс или в отдельной структуре типа или классе. Функции Visual Basic предназначены для оптимального взаимодействия с Visual Basic кодом, а также упрощают чтение исходного кода. Кроме того, методы преобразования платформа .NET Framework не всегда создают те же результаты, что и функции Visual Basic, например при преобразовании Boolean Integer в . Дополнительные сведения см. в разделе «Устранение неполадок типов данных».

Начиная с Visual Basic 15.8, производительность преобразования с плавающей запятой в целочисленное значение оптимизируется при передаче Single или значении, возвращаемых следующими методами в одну из функций преобразования целых чисел ( CByte , , CShort , CInt CLng , CUShort CSByte : CUInt CULng ):Double

Эта оптимизация позволяет коду выполнять большое количество целых преобразований до двух раз быстрее. В следующем примере показаны следующие оптимизированные преобразования с плавающей запятой в целые числа:

Поведение

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

Неудачные преобразования. Если переданный expression функции находится за пределами диапазона типа данных, в который он должен быть преобразован, возникает ошибка OverflowException .

Дробные части. При преобразовании неинтегрального значения в целочисленный тип функции преобразования целых чисел ( CByte , , CInt , , CLng , CSByte , CULng CShort CUInt и CUShort ) удалите дробную часть и округлите значение до ближайшего целого числа.

Если дробная часть равна ровно 0,5, то целочисленное преобразование округляет его до ближайшего даже целого числа. Например, 0,5 округляется до 0, а 1,5 и 2,5 округляется до 2. Иногда это называется округлением банкира, и его целью является компенсация предвзятости, которая может накапливаться при добавлении многих таких чисел вместе.

CInt и CLng отличаются от Int функций Fix , которые усечения, а не округления, дробной части числа. Кроме того, Fix всегда Int возвращается значение того же типа данных, что и при передаче.

Преобразования даты и времени. IsDate Используйте функцию, чтобы определить, можно ли преобразовать значение в дату и время. CDate распознает литералы даты и литералы времени, но не числовые значения. Чтобы преобразовать значение Visual Basic 6.0 Date в Date значение в Visual Basic 2005 или более поздних версиях, можно использовать DateTime.FromOADate этот метод.

Нейтральные значения даты и времени. Тип данных Date всегда содержит сведения о дате и времени. Для преобразования типов Visual Basic считает 1/0001 (1 января 1 года) нейтральным значением даты, а 00:00:00 (полночь) — нейтральным значением для времени. При преобразовании Date значения в строку CStr не включает нейтральные значения в результирующую строку. Например, при преобразовании #January 1, 0001 9:30:00# в строку результатом будет «9:30:00»; сведения о дате подавляются. Однако сведения о дате по-прежнему присутствуют в исходном Date значении и могут быть восстановлены с помощью таких функций, как DatePart функция.

Конфиденциальность языка и региональных параметров. Функции преобразования типов, включающие строки, выполняют преобразования на основе текущих параметров языка и региональных параметров для приложения. Например, CDate распознает форматы дат в соответствии с языковым стандартом системы. Необходимо указать день, месяц и год в правильном порядке для языкового стандарта, или дата может быть неправильно интерпретирована. Длинный формат даты не распознается, если он содержит строку дня недели, например «среда».

Если необходимо преобразовать или из строкового представления значения в формате, отличном от указанного языковым стандартом, нельзя использовать функции преобразования типов Visual Basic. Для этого используйте ToString(IFormatProvider) методы Parse(String, IFormatProvider) этого типа значения. Например, используйте Double.Parse при преобразовании строки в строку Double и используйте Double.ToString при преобразовании значения типа Double в строку.

CType Function

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

Сравнение с другими ключевыми словами CType преобразования типов см. в разделе «Оператор DirectCast » и «Оператор TryCast».

Пример CBool

В следующем примере функция используется CBool для преобразования выражений в Boolean значения. Если выражение принимает ненулевое значение, CBool возвращается True ; в противном случае возвращается False .

Пример CByte

В следующем примере функция используется CByte для преобразования выражения в . Byte

Пример CChar

В следующем примере функция используется CChar для преобразования первого символа String выражения в Char тип.

Входной аргумент CChar должен иметь тип Char данных или String . Нельзя использовать для CChar преобразования числа в символ, так как CChar не удается принять числовой тип данных. В следующем примере получается число, представляющее кодовую точку (код символа) и преобразует ее в соответствующий символ. Она использует InputBox функцию для получения строки цифр, CInt преобразования строки в тип Integer и ChrW преобразования числа в тип Char .

Пример CDate

В следующем примере функция используется CDate для преобразования строк в Date значения. Как правило, не рекомендуется жестко кодировать даты и время в виде строк (как показано в этом примере). Используйте литералы даты и временные литералы, например #Feb 12, 1969# и #4:45:23 PM#.

Пример CDbl

Пример CDec

В следующем примере функция используется CDec для преобразования числового значения в Decimal .

Пример CInt

В следующем примере функция используется CInt для преобразования значения Integer в .

Пример CLng

В следующем примере функция используется CLng для преобразования значений в Long .

Пример CObj

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

Пример CSByte

В следующем примере функция используется CSByte для преобразования числового значения в SByte .

Пример CShort

В следующем примере функция используется CShort для преобразования числового значения в Short .

Пример CSng

В следующем примере функция используется CSng для преобразования значений в Single .

Пример CStr

В следующем примере функция используется CStr для преобразования числового значения в String .

В следующем примере функция используется CStr для преобразования Date значений в String значения.

CStr всегда отображает Date значение в стандартном коротком формате для текущего языкового стандарта, например «6.15.2003 4:35:47 PM». CStr Однако подавляет нейтральные значения 1/1/0001 для даты и 00:00:00 за время.

Дополнительные сведения о значениях, возвращаемых функцией CStr CStr, см. в разделе «Возвращаемые значения».

Пример CUInt

В следующем примере функция используется CUInt для преобразования числового значения в UInteger .

Пример CULng

В следующем примере функция используется CULng для преобразования числового значения в ULong .

Пример CUShort

В следующем примере функция используется CUShort для преобразования числового значения в UShort .

Источник

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()
  • 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:

Numeric Value to Date

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:

Numeric Value to Date

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.

string to integer conversion table

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;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 Sub

The amount can be then used further in your code. The output of this program will be:

string to integer conversion output

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 Sub

And here is the output

decimal to hex conversion 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 below

Sub hexToDec()
    Dim decVal As String, hexVal As String
    hexVal = "270F"
    decVal = Application.WorksheetFunction.Hex2Dec(hexVal)
    MsgBox decVal
End Sub

And the output will be

hex to decimal conversion output

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

Описанные ниже функции позволяют преобразовать переданный параметр, который может быть или числом или строкой к заданному типу данных vba. Отличительная особенность данных функций vba преобразования типов от остальных – префикс C (от слова Convert), после которого следует краткое имя типа данных, к которому происходит преобразование (например, Bool – Boolean, Cur – Currency, и так далее).

CBool(par) – Преобразование к типу Boolean. Если параметр par будет отличаться от 0, то функция вернет значение true, в противном случае – false.

CByte(par) – Преобразование к типу Byte. Параметр par должен содержать числовое значение или строку, которые являются числом без знака в диапазоне значений от 0 до 255. Условия преобразования:

  • Если значение дробной части меньше 0.5, то она будет отброшена. В случае, если дробная часть больше 0.5 – к целой части добавится единица. Если же дробная часть ровна 0.5, то произойдет округление до ближайшего четного числа.
  • Если переданный параметр является строкой, то он должен содержать только цифры, в противном случае произойдет генерация ошибки.
  • В случае, если параметр содержит отрицательное число или число, которое больше 255, то также произойдет генерация ошибки. (vba преобразование типов)

CCur(par) – Преобразование к типу vba Currency. Передаваемый параметр должен содержать значение в диапазоне от -922 337 203 685 477.5808 до 922 337 203 685 477.5807.

Условия преобразования:

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

CDate(par) – Преобразует переданный параметр vba в тип дата.

CDbl(par) – Преобразование к типу vba Double. Переданный параметр должен содержать любое числовое значение или строку, которые входят в диапазон от -1.79769313486232E308 до -4.94065645841247E-324 для отрицательных значений, и от 4.94065645841247E-324 до 1.79769313486232E308 для положительных значений.

Условия преобразования:

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

CDec(par) – Преобразование к типу vba Decimal. Параметр должен содержать любое числовое или строковое значение, входящее в диапазон представляющий целое число в диапазоне +/-79 228 162 514 264 337 593 543 950 335 или смешанное с не более чем 28 цифрами в дробной части в диапазоне +/-7.9228162514264337593543950335. Минимальным возможным ненулевым числом является 0.0000000000000000000000000001.

Условия преобразования:

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

CInt(par) – Преобразование к типу vba Integer. Передаваемый параметр должен входить в диапазон чисел от -32768 до 32767.

Условия преобразования:

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

CLng(par) – Преобразование к типу vba Long, допустимы диапазон передаваемого параметра числа от -2147483648 до 2147483647.

Условия преобразования:

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

CSng(par) – Преобразование к типу vba Single. Допустимый диапазон — число от -3.402823E8 до -1.401298E-45 для отрицательных значений и от 1.401298E-45 до 3.402823E8 для положительных значений.

Условия преобразования:

  • Если передаваемый параметр содержит значение, которое меньше минимального допустимого значения, то функция вернет значение 0.
  • Если параметр содержит значение, которое превышает максимально допустимое, то произойдет генерация ошибки. (vba преобразование типов)
  • Если передаваемый параметр является строкой и содержит не только цифры, то произойдет генерация ошибки.
  • Если число знаков дробной части в параметре выходит за пределы допустимого диапазона, то функция усекает ее (дробную часть).

CStr(par) – Преобразует переданный параметр в строковое значение.

Str(par) — Аналогично функции CStr, но перед положительными числами вставляется пробел.

CVar(par) – Преобразует переданы параметр в тип vba Varint.

CVDate(par) – Фактически, функция аналогична CDate, и используется только для совместимости.

Val(par) — Извлекает из переданного параметра только цифры.

TypeName(par) – Функция возвращает имя типа данных vba, для переданного параметра.

Следующие функции преобразования vba возвращают логические значения true или false, и предназначены для проверки переданного параметра на конкретный тип данных.

IsNumeric(par) — Число

IsDate(par) — Дата

IsArray(par) — Массив

IsEmpty(par) – Тип Empty

IsError(par) — Ошибка

IsMissing(par) – Необязательный параметр, переданный в процедуру

IsNull(par) – Пустое значение

IsObject(par) — Объект

Для преобразования числового значения к восьмеричному или шестнадцатеричному виду, применяются следующие функции:

Hex(par) – Шестнадцатеричный вид.

Oct(par) – Восьмеричный вид.

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

&O – Буква O говорит, что мы хотим прописать восьмеричное значение, которое следует после символа O.

&HA — Буква H говорит, что мы хотим прописать шестнадцатеричное значение, которое следует после символа H.

Так как большая часть приведенных функций используется и в языке VBScript, то примеры с ними можно посмотреть в статьях «Урок 4 по VBScript: преобразование типов данных» и «Урок 10 по VBScript: Функции — математические и для работы с подтипами данных«.

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:
Using the CInt Function in VBA

The following code uses the CLng function to convert a string to an integer:

MsgBox CLng("13.5")

The result is:

Using the CLng Function in VBA

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"

Using the Immediate Window
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:

Converting a String to a Double Decimal Type

The following code would convert a string to a decimal data type:

MsgBox CDec("13.57") + CDec("13.4")

The result is:

Converting a string to a decimal data type in VBA

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:

Using Debug.Print to Display values

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:

Converting a String to the Currency Data Type

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!
vba save as

Learn More!

Понравилась статья? Поделить с друзьями:
  • Vba excel присвоить переменной значение ячеек
  • Vba excel при закрытии формы
  • Vba excel присвоить массив переменной
  • Vba excel при закрытии файла
  • Vba excel прерывание цикла for