Excel vba string to number one

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!

Excel VBA Tutorial about how to convert string to number with macrosIn this VBA Tutorial, you learn how to convert strings to numbers of the Byte, Integer, Long, Single, Double, Currency and Decimal data types.

This VBA Tutorial is accompanied by an Excel workbook containing the macros, data and formulas I use in the examples below. You can get immediate access to this example workbook by subscribing to the Power Spreadsheets Newsletter.

Use the following Table of Contents to navigate to the section that interests you.

Related VBA and Macro Tutorials

The following VBA and Macro Tutorials may help you better understand and implement the contents below:

  • General VBA constructs and structures:
    • Learn about essential VBA terms here.
    • Learn how to work in the Visual Basic Editor here.
    • Learn how to create Sub procedures here.
    • Learn how to create Function procedures here.
    • Learn how to work with variables here.
    • Learn about VBA data types here.
    • Learn about the Range object here.
  • Tutorials about other useful topics:
    • Learn how to work with the IFERROR worksheet function here.

You can find additional VBA and Macro Tutorials in the Archives.

#1: Convert String to Byte

VBA code to convert String to Byte

To convert a string to a number of the Byte data type, use the following statement:

CByte(String)

Process followed by VBA to convert String to Byte

To convert a string to a number of the Byte data type, use the CByte function to convert the String to a number of the Byte data type.

VBA statement explanation

  1. Item: CByte.
    • VBA construct: CByte function.
    • Description: The CByte function coerces String to the Byte data type.

      CByte is usually able to carry out internationally-aware conversions from the String to the Byte data type. In other words, CByte generally recognizes between the different decimal/thousand separators and currency options that depend on your computer’s locale.

      The Byte data type can hold numbers ranging from 0 to 255. If String is outside this range, an error occurs.

  2. Item: String.
    • VBA construct: String expression and expression argument of the CByte function.
    • Description: String is the string or numeric expression you convert to the Byte data type. If you explicitly declare a variable to represent String, use the Variant data type.

Macro example to convert String to Byte

The following macro example, a User-Defined Function, converts a string passed as argument (myString) to Byte.

Function stringToByte(myString As Variant)
    'source: https://powerspreadsheets.com/
    'converts String to Byte
    'for further information: https://powerspreadsheets.com/vba-string-to-number/

    'convert String to Byte
    stringToByte = CByte(myString)

End Function

Effects of executing macro example to convert String to Byte

The following image illustrates the results of using the macro example in a worksheet formula. For these purposes:

  • Column A contains a numeric string.
  • Column B contains a worksheet formula that uses the UDF example.

    When String is outside the range of Byte, the worksheet formula returns the #VALUE! error.

  • Column C displays the worksheet formula used in column B.

Conversion of String to Byte with macro

#2: Convert String to Integer

VBA code to convert String to Integer

To convert a string to a number of the Integer data type, use the following statement:

CInt(String)

Process followed by VBA to convert String to Integer

To convert a string to a number of the Integer data type, use the CInt function to convert the String to a number of the Integer data type.

VBA statement explanation

  1. Item: CInt.
    • VBA construct: CInt function.
    • Description: The CInt function coerces String to the Integer data type.

      If String contains a fraction, CInt rounds it. If this fraction is precisely 0.5, CInt rounds to the nearest even number. For example:

      • 0.5 is rounded to 0.
      • Both 1.5 and 2.5 are rounded to 2.
      • Both 3.5 and 4.5 are rounded to 4.
    • CInt is usually able to carry out internationally-aware conversions from the String to the Integer data type. In other words, CInt generally recognizes between the different decimal/thousand separators and currency options that depend on your computer’s locale.

      The Integer data type can hold numbers ranging from -32,768 to 32,767. If String is outside this range, an error occurs.

  2. Item: String.
    • VBA construct: String expression and expression argument of the CInt function.
    • Description: String is the string or numeric expression you convert to the Integer data type. If you explicitly declare a variable to represent String, use the Variant data type.

Macro example to convert String to Integer

The following macro example, a User-Defined Function, converts a string passed as argument (myString) to Integer.

Function stringToInteger(myString As Variant)
    'source: https://powerspreadsheets.com/
    'converts String to Integer
    'for further information: https://powerspreadsheets.com/vba-string-to-number/

    'convert String to Integer
    stringToInteger = CInt(myString)

End Function

Effects of executing macro example to convert String to Integer

The following image illustrates the results of using the macro example in a worksheet formula. For these purposes:

  • Column A contains a numeric string.
  • Column B contains a worksheet formula that uses the UDF example.

    When String is outside the range of Integer, the worksheet formula returns the #VALUE! error. Additionally, if String contains a fraction that’s precisely 0.5, the UDF rounds to the nearest even number.

  • Column C displays the worksheet formula used in column B.

Conversion of String to Integer with macro

#3: Convert String to Long

VBA code to convert String to Long

To convert a string to a number of the Long data type, use the following statement:

CLng(String)

Process followed by VBA to convert String to Long

To convert a string to a number of the Long data type, use the CLng function to convert the String to a number of the Integer data type.

VBA statement explanation

  1. Item: CLng.
    • VBA construct: CLng function.
    • Description: The CLng function coerces String to the Long data type.

      If String contains a fraction, CLng rounds it. If this fraction is precisely 0.5, CLng rounds to the nearest even number. For example:

      • 0.5 is rounded to 0.
      • Both 1.5 and 2.5 are rounded to 2.
      • Both 3.5 and 4.5 are rounded to 4.

      CLng is usually able to carry out internationally-aware conversions from the String to the Long data type. In other words, CLng generally recognizes between the different decimal/thousand separators and currency options that depend on your computer’s locale.

      The Long data type can hold numbers ranging from -2,147,483,648 to 2,147,483,647. If String is outside this range, an error occurs.

  2. Item: String.
    • VBA construct: String expression and expression argument of the CLng function.
    • Description: String is the string or numeric expression you convert to the Long data type. If you explicitly declare a variable to represent String, use the Variant data type.

Macro example to convert String to Long

The following macro example, a User-Defined Function, converts a string passed as argument (myString) to Long.

Function stringToLong(myString As Variant)
    'source: https://powerspreadsheets.com/
    'converts String to Long
    'for further information: https://powerspreadsheets.com/vba-string-to-number/

    'convert String to Long
    stringToLong = CLng(myString)

End Function

Effects of executing macro example to convert String to Long

The following image illustrates the results of using the macro example in a worksheet formula. For these purposes:

  • Column A contains a numeric string.
  • Column B contains a worksheet formula that uses the UDF example.

    When String is outside the range of Long, the worksheet formula returns the #VALUE! error. Additionally, if String contains a fraction that’s precisely 0.5, the UDF rounds to the nearest even number.

  • Column C displays the worksheet formula used in column B.

Conversion of String to Long with macro

#4: Convert String to Single

VBA code to convert String to Single

To convert a string to a number of the Single data type, use the following statement:

CSng(String)

Process followed by VBA to convert String to Single

To convert a string to a number of the Single data type, use the CSng function to convert the String to a number of the Single data type.

VBA statement explanation

  1. Item: CSng.
    • VBA construct: CSng function.
    • Description: The CSng function coerces String to the Single data type.

      CSng is usually able to carry out internationally-aware conversions from the String to the Single data type. In other words, CSng generally recognizes between the different decimal/thousand separators and currency options that depend on your computer’s locale.

      The Single data type can hold floating-point numbers ranging from:

      • -3.402823E38 to -1.401298E-45 for negative values; and
      • 1.401298E-45 to 3.402823E38 for positive values.

      If String is outside the required range, an error occurs.

  2. Item: String.
    • VBA construct: String expression and expression argument of the CSng function.
    • Description: String is the string or numeric expression you convert to the Single data type. If you explicitly declare a variable to represent String, use the Variant data type.

Macro example to convert String to Single

The following macro example, a User-Defined Function, converts a string passed as argument (myString) to Single.

Function stringToSingle(myString As Variant)
    'source: https://powerspreadsheets.com/
    'converts String to Single
    'for further information: https://powerspreadsheets.com/vba-string-to-number/

    'convert String to Single
    stringToSingle = CSng(myString)

End Function

Effects of executing macro example to convert String to Single

The following image illustrates the results of using the macro example in a worksheet formula. For these purposes:

  • Column A contains a numeric string.
  • Column B contains a worksheet formula that uses the UDF example.

    When String is outside the range of Single, the worksheet formula returns the #VALUE! error.

  • Column C displays the worksheet formula used in column B.

Conversion of String to Single with macro

#5: Convert String to Double

VBA code to convert String to Double

To convert a string to a number of the Double data type, use the following statement:

CDbl(String)

Process followed by VBA to convert String to Double

To convert a string to a number of the Double data type, use the CDbl to convert the String to a number of the Double data type.

VBA statement explanation

  1. Item: CDbl.
    • VBA construct: CDbl function.
    • Description: The CDbl function coerces String to the Double data type.

      CDbl is usually able to carry out internationally-aware conversions from the String to the Double data type. In other words, CDbl generally recognizes between the different decimal/thousand separators and currency options that depend on your computer’s locale.

      The Double data type can hold floating-point numbers ranging from:

      • -1.79769313486231E308 to -4.94065645841247E-324 for negative values; and
      • 4.94065645841247E-324 to 1.79769313486232E308 for positive values.

      If String is outside the required range, an error occurs.

  2. Item: String.
    • VBA construct: String expression and expression argument of the CDbl function.
    • Description: String is the string or numeric expression you convert to the Double data type. If you explicitly declare a variable to represent String, use the Variant data type.

Macro example to convert String to Double

The following macro example, a User-Defined Function, converts a string passed as argument (myString) to Double.

Function stringToDouble(myString As Variant)
    'source: https://powerspreadsheets.com/
    'converts String to Double
    'for further information: https://powerspreadsheets.com/vba-string-to-number/

    'convert String to Double
    stringToDouble = CDbl(myString)

End Function

Effects of executing macro example to convert String to Double

The following image illustrates the results of using the macro example in a worksheet formula. For these purposes:

  • Column A contains a numeric string.
  • Column B contains a worksheet formula that uses the UDF example.

    When String is outside the range of Double, the worksheet formula returns the #VALUE! error.

  • Column C displays the worksheet formula used in column B.

Conversion of String to Double with macro

#6: Convert String to Currency

VBA code to convert String to Currency

To convert a string to a number of the Currency data type, use the following statement:

CCur(String)

Process followed by VBA to convert String to Currency

To convert a string to a number of the Currency data type, use the CCur to convert the String to a number of the Currency data type.

VBA statement explanation

  1. Item: CCur.
    • VBA construct: CCur function.
    • Description: The CCur function coerces String to the Currency data type.

      CCur is usually able to carry out internationally-aware conversions from the String to the Currency data type. In other words, CCur generally recognizes between the different decimal/thousand separators and currency options that depend on your computer’s locale.

      The Currency data type holds integers scaled by 10,000. This results in Currency holding fixed-point numbers with 15 digits to the left of the decimal point and 4 digits to the right of the decimal point. Therefore, Currency can hold numbers ranging from -922,337,203,685,477.5808 to 922,337,203,685,477.5807. If String is outside this range, an error occurs.

  2. Item: String.
    • VBA construct: String expression and expression argument of the CCur function.
    • Description: String is the string or numeric expression you convert to the Currency data type. If you explicitly declare a variable to represent String, use the Variant data type.

Macro example to convert String to Currency

The following macro example, a User-Defined Function, converts a string passed as argument (myString) to Currency.

Function stringToCurrency(myString As Variant)
    'source: https://powerspreadsheets.com/
    'converts String to Currency
    'for further information: https://powerspreadsheets.com/vba-string-to-number/

    'convert String to Currency
    stringToCurrency = CCur(myString)

End Function

Effects of executing macro example to convert String to Currency

The following image illustrates the results of using the macro example in a worksheet formula. For these purposes:

  • Column A contains a numeric string.
  • Column B contains a worksheet formula that uses the UDF example.

    When String is outside the range of Currency, the worksheet formula returns the #VALUE! error.

  • Column C displays the worksheet formula used in column B.

Conversion of String to Currency with macro

#7: Convert String to Decimal

VBA code to convert String to Decimal

To convert a string to a number of the Decimal data type, use the following statement:

CDec(String)

Process followed by VBA to convert String to Decimal

To convert a string to a number of the Decimal data type, use the CDec function to convert the String to a number of the Decimal data type.

VBA statement explanation

  1. Item: CDec.
    • VBA construct: CDec function.
    • Description: From a broad perspective, the CDec function coerces String to the Decimal data subtype of the Variant data type. In other words, CDec doesn’t return a discrete data type, but rather a Variant converted to the Decimal subtype.

      CDec is usually able to carry out internationally-aware conversions from the String to the Decimal data type. In other words, CDec generally recognizes between the different decimal/thousand separators and currency options that depend on your computer’s locale.

      The Decimal data type holds integers scaled by a variable power of 10. This power of 10 specifies the number of digits to the right of the decimal point. Therefore, the value ranges Decimal can hold are as follows:

      • When working with a scale of 0, which results in no decimal places: -79,228,162,514,264,337,593,543,950,335 to 79,228,162,514,264,337,593,543,950,335.
      • When working with 28 decimal places:
        • The largest and smallest values are +7.9228162514264337593543950335 and -7.9228162514264337593543950335.
        • The smallest non-zero values are -0.0000000000000000000000000001 and 0.0000000000000000000000000001.

      If String is outside the required range, an error occurs.

  2. Item: String.
    • VBA construct: String expression and expression argument of the CDec function.
    • Description: String is the string or numeric expression you convert to the CDec data type. If you explicitly declare a variable to represent String, use the Variant data type.

Macro example to convert String to Decimal

The following macro example, a User-Defined Function, converts a string passed as argument (myString) to Decimal.

Function stringToDecimal(myString As Variant)
    'source: https://powerspreadsheets.com/
    'converts String to Decimal
    'for further information: https://powerspreadsheets.com/vba-string-to-number/

    'convert String to Decimal
    stringToDecimal = CDec(myString)

End Function

Effects of executing macro example to convert String to Decimal

The following image illustrates the results of using the macro example in a worksheet formula. For these purposes:

  • Column A contains a numeric string.
  • Column B contains a worksheet formula that uses the UDF example.

    When String is outside the range of Decimal, the worksheet formula returns the #VALUE! error.

  • Column C displays the worksheet formula used in column B.

Conversion of String to Decimal with macro

Numeric values are defined by data types like integer or byte. These data types are used for optimizing the processing and memory allocation in Excel. In this guide, we’re going to show you how to convert string into number in Excel VBA.

Download Workbook

Data types in VBA

Like in some other programming languages, VBA uses data types to identify what variables it can store and how they are stored. Most of the data types in VBA define numeric values. Here is a brief list of numeric data types:

Data type Storage Range
Byte 1 byte 0 to 255
Integer 2 bytes -32,768 to 32,767
Long 4 bytes -2,147,483,648 to 2,147,483,647
Single 4 bytes -3.402823E38 to -1.401298E-45 for negative values; 1.401298E-45 to 3.402823E38 for positive values
Double 8 bytes -1.79769313486231E308 to-4.94065645841247E-324 for negative values; 4.94065645841247E-324 to 1.79769313486232E308 for positive values
LongLong 8 bytes

-9,223,372,036,854,775,808 to 9,223,372,036,854,775,807

Valid on 64-bit platforms only.

Currency 8 bytes -922,337,203,685,477.5808 to 922,337,203,685,477.5807
Decimal 14 bytes +/-79,228,162,514,264,337,593,543,950,335 with no decimal point;
+/-7.9228162514264337593543950335 with 28 places to the right of the decimal

Since there are many numeric data types, there are many functions to convert a string into number in Excel VBA.

Functions to a convert string into number in Excel VBA

All conversion functions use the same syntax: Each requires a single string argument to convert into a number. For example:

Each function returns an error If the string argument either is not a numeric or is outside the range of the data type being converted.

CInt(«A») returns a type mismatch error, because the «A» is not a numeric value.

CByte(«1250») returns an overflow exception.

Function Return type Example
CByte Byte CByte(«65.75») returns 66
CCur Currency CCur(«$256,000.50») returns 256000.5
CDbl Double CDbl(128.239856 * 4.8 * 0.04) returns 24.622052352
CDec Decimal CDec(«15000000.5678») returns 15000000.5678
CInt Integer CInt(«1234.56») returns 1235
CLng Long CLng(«1,500,000.88») returns 15000001
CLngLng LongLong CLngLng(«1,250,500,000.88») returns 1250500001
CSng Single CSng(«5.67854») returns 5.67854

Bonus: Use IsNumeric function to verify value

To avoid type mismatch errors, you can use the IsNumeric function to check if the expression is numeric or not. The function returns Boolean value based on the expression. TRUE if the expression is numeric, FALSE otherwise.

Here is a sample function that can check the data first, and convert the it into an integer if it is numeric. If the argument is not a valid number, the function returns 0.

Function ConvertInt(arg As String) As Integer
 If IsNumeric(arg) Then ConvertInt = CInt(arg)
End Function

Содержание

  1. VBA Convert Text String to Number
  2. Convert String to Integer
  3. Convert String to Decimal
  4. Convert String to Currency
  5. VBA Coding Made Easy
  6. VBA Code Examples Add-in
  7. Функции преобразования типов
  8. Синтаксис
  9. Возвращаемые типы
  10. Примечания
  11. Пример функции CBool
  12. Пример функции CByte
  13. Пример функции CCur
  14. Пример функции CDate
  15. Пример функции CDbl
  16. Пример функции CDec
  17. Пример функции CInt
  18. Пример функции CLng
  19. Пример функции CSng
  20. Пример функции CStr
  21. Пример функции CVar
  22. См. также
  23. Поддержка и обратная связь
  24. VBA Excel. Преобразование текста в число
  25. Преобразование текста в число
  26. Преобразование смешанной строки
  27. Массовое преобразование чисел

VBA Convert Text String to Number

In this Article

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:

The result is:

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

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:


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:

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:

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

You can use the Immediate Window to see how the value would be processed if not converted to a double or decimal data type:

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:

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 Code Examples Add-in

Easily access all of the code examples found on our site.

Simply navigate to the menu, click, and the code will be inserted directly into your module. .xlam add-in.

Источник

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

Каждая функция приводит выражение к нужному типу данных.

Синтаксис

  • CBool(выражение)
  • CByte(выражение)
  • CCur(выражение)
  • CDate(выражение)
  • CDbl(выражение)
  • CDec(выражение)
  • CInt(выражение)
  • CLng(выражение)
  • CLngLng(выражение) (действительно только для 64-разрядных платформ).
  • CLngPtr(выражение)
  • CSng(выражение)
  • CStr(выражение)
  • CVar(выражение)

Обязательный аргумент выражение — это любое строковое или числовое выражение.

Возвращаемые типы

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

Функция Тип возвращаемых данных Диапазон выражения-аргумента
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, дробная часть округляется.
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-разрядных систем; дробная часть округляется в обоих типах систем.
CSng Single От -3,402823E38 до -1,401298E-45 для отрицательных значений; от 1,401298E-45 до 3,402823E38 для положительных значений.
CStr String Результат, возвращаемый функцией CStr, зависит от аргумента выражение.
CVar Variant Диапазон совпадает с типом Double для числовых значений и с типом String для нечисловых значений.

Примечания

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

Для явного присвоения значений типа LongLong (включая тип LongPtr на 64-разрядных платформах) целочисленным типам данных меньшего размера должны использоваться функции преобразования. Неявные преобразования типа LongLong в меньшие целочисленные типы не допускаются.

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

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

Если дробная часть целого числа строго равна 0,5, функции CInt и CLng всегда округляют результат до ближайшего четного числа. Например, 0,5 округляется до 0, а 1,5 — до 2. Функции CInt и CLng отличаются от функций Fix и Int, которые отбрасывают дробную часть числа, а не округляют ее. Кроме того, функции Fix и Int всегда возвращают значение того же типа, что и переданное им выражение.

Для определения возможности преобразования date в дату или время используется функция IsDate. Функция CDate распознает литералы даты и времени, а также некоторые числа, которые находятся в диапазоне допустимых дат. При преобразовании числа в дату преобразуется целая часть числа. Дробная часть преобразуется во время суток, начиная с полуночи.

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

Функция CVDate предназначена для обеспечения совместимости с предыдущими версиями Visual Basic. Синтаксис функции CVDate не отличается от синтаксиса функции CDate; однако функция CVDate возвращает тип Variant, подтипом которого является тип Date, а не собственно тип Date. Поскольку теперь реализован встроенный тип Date, необходимость в функции CVDate отпадает. Такой же результат можно получить, если преобразовать выражение в тип Date и присвоить его типу Variant. Этот способ позволяет преобразовать все прочие встроенные типы в эквивалентные им подтипы Variant.

Функция CDec не возвращает отдельный тип данных. Вместо этого она всегда возвращает результат типа Variant, значение которого преобразовано в подтип Decimal.

Пример функции CBool

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

Пример функции CByte

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

Пример функции CCur

В этом примере функция CCur используется для преобразования выражения в тип Currency.

Пример функции CDate

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

Пример функции CDbl

В этом примере функция CDbl используется для преобразования выражения в тип Double.

Пример функции CDec

В этом примере функция CDec используется для преобразования выражения в тип Decimal.

Пример функции CInt

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

Пример функции CLng

В этом примере функция CLng используется для преобразования выражения в тип Long.

Пример функции CSng

В этом примере функция CSng используется для преобразования выражения в тип Single.

Пример функции CStr

В этом примере функция CStr используется для преобразования выражения в тип String.

Пример функции CVar

В этом примере функция CVar используется для преобразования выражения в тип Variant.

См. также

Поддержка и обратная связь

Есть вопросы или отзывы, касающиеся Office VBA или этой статьи? Руководство по другим способам получения поддержки и отправки отзывов см. в статье Поддержка Office VBA и обратная связь.

Источник

VBA Excel. Преобразование текста в число

Преобразование текста в число с помощью кода VBA Excel. Массовое преобразование чисел из текстового формата в числовой в заданном диапазоне.

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

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

  • ячеек рабочего листа с текстовым форматом;
  • элементов управления формы (TextBox, ListBox, ComboBox);
  • строковых переменных;
  • выражений, возвращающих число в виде текста;
  • текстового поля функции InputBox.

В большинстве случаев VBA Excel сам распознает текст как число без всяких преобразований:

Обратите внимание на разделитель дробной части.

Преобразование смешанной строки

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

Массовое преобразование чисел

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

Пример преобразования диапазона ячеек с текстовым форматом в общий формат и значений ячеек из строки в число на примере объекта Selection:

Сначала выбранному диапазону присваивается общий формат ( «General» ). Но текстовые значения в ячейках еще не преобразовались в числа. Обходим циклом все ячейки диапазона, и, если текстовое значение ячейки можно интерпретировать как число, умножаем это значение на единицу. После этого текст будет преобразован в число.

Источник

Convert String to Number in VBA

This article will discuss how we can convert a string to a number in VBA Excel. There is a step-by-step guide and many examples for our understanding.

Convert String to Number in VBA

In VBA code, converting numbers saved as text to real numbers is obligatory. We have many conversion options.

We can convert strings to numbers of the Byte, Integer, Long, Single, Double, Currency, and Decimal data types. We will discuss each conversion in detail with examples.

Convert String to Byte in VBA

We can easily transform a string into a number of the byte data type with the help of the following code.

# vba
byte = CByte(str)

We can use the CByte() function to achieve this conversion. The above statement has two items: CByte() and string.

CByte() function forces the string to change into a byte type. CByte() is often used to perform the internationally-aware string transformation to byte data type.

In simple terms, CByte() commonly distinguishes distinctive decimal/thousand separators and many currency options that hinge upon your computer’s location. The range that a byte data type can hold is 0 to 225. If your string does not fall in between this range, an error will occur.

Here is a macro example in which we have convertStr as an argument to convert a string to a byte.

# vba
Function convertStr(newStr As Variant)

    MsgBox (CByte(newStr))

End Function

Sub newFunc()
convertStr ("12")
End Sub

Output:

convert string to number as byte in VBA

Convert String to Integer in VBA

With the help of the following statement, you can easily convert a string to a number of the integer data type. The syntax of this function is shown below.

# vba
CInt(newStr)

It is recommended to use the Clnt() function to change a string to an integer data type. This function forces the string to change into the integer data type.

If a string holds a fraction, this function will convert it into an integer. If the fraction is precisely 0.4, this function will change it to the closest even number.

For example:

# vba
0.4 will become 0.
1.6 and 2.4 both will become 2.
3.7 and 4.3 will become 4

Clnt() is often used to perform the internationally-aware string transformation into the integer data type. In simple terms, Clnt() commonly distinguishes distinctive decimal/thousand separators and many currency options that hinge upon our computer’s location.

The range between which an integer data type can hold numbers is -32,768 to 32,767. If your string does not fall in between this range, an error will occur.

Let’s go through an example and use the CInt() function as shown below. This example sets newStr as an argument to change a string into an integer, as shown below.

# vba
Function convertToInteger(newStr As Variant)

    MsgBox (CInt(newStr))

End Function

Sub newFunc()
convertToInteger ("12.5")
End Sub

Output:

convert string to number as int in VBA

Convert String to Long in VBA

We can use the CLng() function to achieve this conversion. The syntax of this function is shown below.

# vba
CLng(Str)

We can use the CLng() function when our goal is to change a string into several long data types. The items in this statement are CLng() and string.

This function forces a string to change into the long data type.

If a string holds a fraction, this function will round it. If the fraction is precisely 0.4, this function will change it to the closest even number, as shown below.

# vba
0.4 will become 0.
1.6 and 2.4 both will become 2.
3.7 and 4.3 will become 4

CLng() is often used to perform the internationally-aware string transformation to long data types. In simple terms, CLng() commonly distinguishes distinctive decimal/thousand separators and many currency options that hinge upon your computer’s location.

The range between which an integer data type can hold numbers is -2,147,483,648 to 2,147,483,647. If your string does not fall in between this range, an error will occur.

Let’s go through an example and use the CLng() function. In this example, we have set newStr as an argument to change a string into long, as shown below.

# vba
Function convertToLong(newStr As Variant)

    MsgBox (CLng(newStr))

End Function

Sub newFunc()
convertToLong ("15.7")
End Sub

Output:

convert string to number as long in VBA

Long data type differs from integer data type by only one thing. Larger numbers are acceptable in long data types.

But there wasn’t enough memory in the old days, and it was not recommended to use long data types.

In modern times, memory is no longer a problem. We can use the long data type instead of an integer.

Convert String to Single in VBA

We can easily transform a string into a number of a single data type with the help of the following syntax, as shown below.

# vba
CSng(str)

We can use the CSng() function to achieve this conversion. There are two items in the above statement, CSng() and string.

This function forces a string to change into a single data type.

CSng() is often used to perform the internationally-aware string transformation to a single data type. CSng() commonly distinguishes distinctive decimal/thousand separators and currency options that hinge upon your computer’s location.

The range between which a single data type can hold floating-point numbers is

  • 3.402823E38 to -1.401298E-45 when values are negative
  • 1.401298E-45 to 3.402823E38 when values are positive

An error will appear if your string does not fall between this range. As shown below, let’s go through an example in which we set newStr as an argument to change a string into a single.

# vba
Function convertToSingle(newStr As Variant)

    MsgBox (CSng(newStr))

End Function

Sub newFunc()
convertToSingle ("1.3")
End Sub

Output:

convert string to number as single in VBA

Convert String to Double in VBA

With the help of the following statement, we can easily convert a string to several double data types. The syntax of this function is as shown below.

# vba
CDbl(str)

It is recommended to use the CDbl() function to change a string to a double data type. This function forces a string to change into the double data type.

CDbl() is often used to perform the internationally-aware string transformation to a double data type.

In simple words, CDbl() commonly distinguishes distinctive decimal/thousand separators and many currency options that hinge upon your computer’s location.

The range between which a double data type can hold floating-point numbers is below.

  • -1.79769313486231E308 to -4.94065645841247E-324 when values are negative.
  • 4.94065645841247E-324 to 1.79769313486232E308 when values are positive.

An error will appear if our string does not fall between this range. As shown below, let’s go through an example in which we set newStr as an argument to change a string into a double.

# vba
Function convertToDouble(newStr As Variant)

    MsgBox (CDbl(newStr))

End Function

Sub newFunc()
convertToDouble ("1.345")
End Sub

Output:

convert string to number as double in VBA

Convert String to Currency in VBA

With the help of the following statement, you can easily convert a string to several currency data types. The syntax of the function is shown below.

# vba
CCur(newStr)

It is recommended to use the CCur() function to change a string to a currency data type. This function forces a string to change into the currency data type.

CCur() is often used to perform the internationally-aware string transformation to a currency data type.

It means CCur() commonly distinguishes distinctive decimal/thousand separators and many currency options that hinge upon your computer’s location. The currency data type can hold integers by 10,000.

As a result, a currency can hold 15 numbers to the left of the decimal point and four numbers to the right of the decimal point. So the range between which a currency can hold numbers is:
-922,337,203,685,477.5808 to 922,337,203,685,477.5807.

An error will appear if your string does not fall between this range.

As shown below, let’s go through an example in which we set newStr as an argument to change a string into a currency.

# vba
Function convertToCurrency(newStr As Variant)

    msgBox(CCur(newStr))

End Function

Convert String to Decimal in VBA

We can use the following statement to achieve this conversion.

# vba
CDec(newStr)

We can use the CDec() function when our goal is to change a string into several decimal data types. This function forces a string to change into the decimal data subtype of the Variant data type.

In simple words, CDec() will return a variant changed to the Decimal subtype.

CDec() is often used to perform the internationally-aware transformation of a string to a decimal data type. It means CDec() commonly distinguishes distinctive decimal/thousand separators and many currency options that hinge upon your computer’s location.

The decimal data type can carry integers having variable power of 10. The power denotes the number of digits that can be present to the right of the decimal point.

The range in which decimals can hold values is shown below.

  • When the scale is 0, that is no decimal present the range is from 79,228,162,514,264,337,593,543,950,335 to 79,228,162,514,264,337,593,543,950,335.
  • When there are 28 decimal places, the biggest and smallest values are +7.9228162514264337593543950335 and -7.9228162514264337593543950335.
  • The smallest values containing no zero values are -0.0000000000000000000000000001 and 0.0000000000000000000000000001.

As shown below, let’s go through an example in which we set newStr as an argument to change a string into a decimal.

# vba
Function convertToDecimal(newStr As Variant)

    msgBox(CDec(newStr))

End Function

Понравилась статья? Поделить с друзьями:
  • Excel vba string to long
  • Excel vba string not in array
  • Excel vba string array to string
  • Excel vba str to int
  • Excel vba stop vba