Excel vba number from string

Watch Video – How to Extract Numbers from text String in Excel (Using Formula and VBA)

There is no inbuilt function in Excel to extract the numbers from a string in a cell (or vice versa –  remove the numeric part and extract the text part from an alphanumeric string).

However, this can be done using a cocktail of Excel functions or some simple VBA code.

Let me first show you what I am talking about.

Suppose you have a data set as shown below and you want to extract the numbers from the string (as shown below):

Extract Number from String in Excel - Data

The method you choose will also depend on the version of Excel you’re using:

  • For versions prior to Excel 2016, you need to use slightly longer formulas
  • For Excel 2016, you can use the newly introduced TEXTJOIN function
  • VBA method can be used in all the versions of Excel

Click here to download the example file

Extract Numbers from String in Excel (Formula for Excel 2016)

This formula will work only in Excel 2016 as it uses the newly introduced TEXTJOIN function.

Also, this formula can extract the numbers that are at the beginning, end or middle of the text string.

Note that the TEXTJOIN formula covered in this section would give you all the numeric characters together. For example, if the text is “The price of 10 tickets is USD 200”, it will give you 10200 as the result.

Suppose you have the dataset as shown below and you want to extract the numbers from the strings in each cell:

Below is the formula that will give you numeric part from a string in Excel.

=TEXTJOIN("",TRUE,IFERROR((MID(A2,ROW(INDIRECT("1:"&LEN(A2))),1)*1),""))

Formula to get all number from a string

This is an array formula, so you need to use ‘Control + Shift + Enter‘ instead of using Enter.

In case there are no numbers in the text string, this formula would return a blank (empty string).

How does this formula work?

Let me break this formula and try and explain how it works:

  • ROW(INDIRECT(“1:”&LEN(A2))) – this part of the formula would give a series of numbers starting from one. The LEN function in the formula returns the total number of characters in the string. In the case of “The cost is USD 100”, it will return 19. The formulas would thus become ROW(INDIRECT(“1:19”). The ROW function will then return a series of numbers – {1;2;3;4;5;6;7;8;9;10;11;12;13;14;15;16;17;18;19}
  • (MID(A2,ROW(INDIRECT(“1:”&LEN(A2))),1)*1) – This part of the formula would return an array of #VALUE! errors or numbers based on the string. All the text characters in the string become #VALUE! errors and all numerical values stay as-is. This happens as we have multiplied the MID function with 1.
  • IFERROR((MID(A2,ROW(INDIRECT(“1:”&LEN(A2))),1)*1),””) – When IFERROR function is used, it would remove all the #VALUE! errors and only the numbers would remain. The output of this part would look like this – {“”;””;””;””;””;””;””;””;””;””;””;””;””;””;””;””;1;0;0}
  • =TEXTJOIN(“”,TRUE,IFERROR((MID(A2,ROW(INDIRECT(“1:”&LEN(A2))),1)*1),””)) – The TEXTJOIN function now simply combines the string characters that remains (which are the numbers only) and ignores the empty string.

Pro Tip: If you want to check the output of a part of the formula, select the cell, press F2 to get into the edit mode, select the part of the formula for which you want the output and press F9. You will instantly see the result. And then remember to either press Control + Z or hit the Escape key. DO NOT hit the enter key.

Download the Example File

You can also use the same logic to extract the text part from an alphanumeric string. Below is the formula that would get the text part from the string:

=TEXTJOIN("",TRUE,IF(ISERROR(MID(A2,ROW(INDIRECT("1:"&LEN(A2))),1)*1),MID(A2,ROW(INDIRECT("1:"&LEN(A2))),1),""))

A minor change in this formula is that IF function is used to check if the array we get from MID function are errors or not. If it’s an error, it keeps the value else it replaces it with a blank.

Then TEXTJOIN is used to combine all the text characters.

Caution: While this formula works great, it uses a volatile function (the INDIRECT function). This means that in case you use this with a huge dataset, it may take some time to give you the results. It’s best to create a backup before you use this formula in Excel.

Extract Numbers from String in Excel (for Excel 2013/2010/2007)

If you have Excel 2013. 2010. or 2007, you can not use the TEXTJOIN formula, so you will have to use a complicated formula to get this done.

Suppose you have a dataset as shown below and you want to extract all the numbers in the string in each cell.

Extract Number from String in Excel - Data

The below formula will get this done:

=IF(SUM(LEN(A2)-LEN(SUBSTITUTE(A2, {"0","1","2","3","4","5","6","7","8","9"}, "")))>0, SUMPRODUCT(MID(0&A2, LARGE(INDEX(ISNUMBER(--MID(A2,ROW(INDIRECT("$1:$"&LEN(A2))),1))* ROW(INDIRECT("$1:$"&LEN(A2))),0), ROW(INDIRECT("$1:$"&LEN(A2))))+1,1) * 10^ROW(INDIRECT("$1:$"&LEN(A2)))/10),"")

In case there is no number in the text string, this formula would return blank (empty string).

Although this is an array formula, you don’t need to use ‘Control-Shift-Enter’ to use this. A simple enter works for this formula.

Credit to this formula goes to the amazing Mr. Excel forum.

Again, this formula will extract all the numbers in the string no matter the position. For example, if the text is “The price of 10 tickets is USD 200”, it will give you 10200 as the result.

Caution: While this formula works great, it uses a volatile function (the INDIRECT function). This means that in case you use this with a huge dataset, it may take some time to give you the results. It’s best to create a backup before you use this formula in Excel.

Separate Text and Numbers in Excel Using VBA

If separating text and numbers (or extracting numbers from the text) is something you have to often, you can also use the VBA method.

All you need to do is use a simple VBA code to create a custom User Defined Function (UDF) in Excel, and then instead of using long and complicated formulas, use that VBA formula.

Let me show you how to create two formulas in VBA – one to extract numbers and one to extract text from a string.

Extract Numbers from String in Excel (using VBA)

In this part, I will show you how to create the custom function to get only the numeric part from a string.

Below is the VBA code we will use to create this custom function:

Function GetNumeric(CellRef As String)
Dim StringLength As Integer
StringLength = Len(CellRef)
For i = 1 To StringLength
If IsNumeric(Mid(CellRef, i, 1)) Then Result = Result & Mid(CellRef, i, 1)
Next i
GetNumeric = Result
End Function

Here are the steps to create this function and then use it in the worksheet:

Now, you will be able to use the GetText function in the worksheet. Since we have done all the heavy lifting in the code itself, all you need to do is use the formula =GetNumeric(A2). 

This will instantly give you only the numeric part of the string.

Using Custom VBA Function to get only the numeric part from a string in Excel

Note that since the workbook now has VBA code in it, you need to save it with .xls or .xlsm extension.

Download the Example File

In case you have to use this formula often, you can also save this to your Personal Macro Workbook. This will allow you to use this custom formula in any of the Excel workbooks that you work with.

Extract Text from a String in Excel (using VBA)

In this part, I will show you how to create the custom function to get only the text part from a string.

Below is the VBA code we will use to create this custom function:

Function GetText(CellRef As String)
Dim StringLength As Integer
StringLength = Len(CellRef)
For i = 1 To StringLength
If Not (IsNumeric(Mid(CellRef, i, 1))) Then Result = Result & Mid(CellRef, i, 1)
Next i
GetText = Result
End Function

Here are the steps to create this function and then use it in the worksheet:

Now, you will be able to use the GetNumeric function in the worksheet. Since we have done all the heavy lifting in the code itself, all you need to do is use the formula =GetText(A2).

This will instantly give you only the numeric part of the string.

Using Custom VBA Function to get only the Text part from a string in Excel

Note that since the workbook now has VBA code in it, you need to save it with .xls or .xlsm extension.

In case you have to use this formula often, you can also save this to your Personal Macro Workbook. This will allow you to use this custom formula in any of the Excel workbooks that you work with.

In case you’re using Excel 2013 or prior versions and don’t have

You May Also Like the Following Excel Tutorials:

  • CONCATENATE Excel Ranges (with and without separator).
  • A Beginner’s Guide to Using For Next Loop in Excel VBA.
  • Using Text to Columns in Excel.
  • How to Extract a Substring in Excel (Using TEXT Formulas).
  • Excel Macro Examples for VBA Beginners.
  • Separate Text and Numbers in Excel

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

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!

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

When we develop VBA applications, sometimes we need to develop functions or subroutines to extract numbers from strings. So in this lesson you will learn a few different ways to extract numbers from a string using VBA.

Assume we have a string like this.

234sTsur45$p^

We are going to learn how to extract only 23445 from the above text string. There are few different ways to do this.

In this method we are going to use an inbuilt function called “IsNumeric” to extract only numbers from the string. Let’s name this subroutine as ExtractNumbers.

Sub ExtractNumbers()

End Sub

First we need to declare a few variables.

Dim MyString As String
Dim Tmp_Char As String
Dim ResultString As String
Dim i As Integer

Then we can assign our string to the MyString variable.

MyString = «234sTsur45$p^»

Next we need a For Next statement to iterate through each character of the string.

For i = 1 To Len(MyString)

Next i

Inside this For Next statement we can use the Mid function to extract each character one by one. Each character will be assigned to the Tmp_Char variable temporarily.

For i = 1 To Len(MyString)
     Tmp_Char = Mid(MyString, i, 1)
Next i

Now use IsNumeric function inside an If statement to check whether each character is a value or not. If the IsNumeric function returns true then we add that number to the ResultString variable.

For i = 1 To Len(MyString)
     Tmp_Char = Mid(MyString, i, 1)
     If IsNumeric(Tmp_Char) = True Then
         ResultString = ResultString & Tmp_Char
     End If
Next i

Want to learn more about the IsNumeric function? Check this post.

IsNumeric Function

This is the complete code of the first method.

Sub ExtractNumbers()

     Dim MyString As String
     Dim Tmp_Char As String
     Dim ResultString As String
     Dim i As Integer

     MyString = «234sTsur45$p^»

     For i = 1 To Len(MyString)
         Tmp_Char = Mid(MyString, i, 1)
         If IsNumeric(Tmp_Char) = True Then
             ResultString = ResultString & Tmp_Char
         End If
     Next i

     Debug.Print ResultString

End Sub

23445 will be printed in the immediate window when you run the above subroutine.

Numbers are extracted from the string

In this method we are going to use Select Case statement instead of the If statement and IsNumeric function to extract numbers from the string. Below is the complete code of the second method.

Sub ExtractNumbers_Method2()

     Dim MyString As String
     Dim Tmp_Char As String
     Dim ResultString As String
     Dim i As Integer

     MyString = «234sTsur45$p^»

     For i = 1 To Len(MyString)
         Tmp_Char = Mid(MyString, i, 1)
         Select Case Tmp_Char
         Case 0 To 9
             ResultString = ResultString & Tmp_Char
         End Select
     Next i

     Debug.Print ResultString

End Sub

In this method Select Case statement is used to check whether the character is equal to value from 0 to 9. If the character is equal to value from 0 to 9 then those characters are appended to the ResultString.

Like this post? Please share to your friends:
  • Excel vba number format number
  • Excel vba is not numeric
  • Excel vba is keyword
  • Excel vba now time
  • Excel vba is decimal