Vba excel text to number one

I have columns of numbers that, for whatever reason, are formatted as text. This prevents me from using arithmetic functions such as the subtotal function. What is the best way to convert these «text numbers» to true numbers?

Here is a screenshot of the specific issue:
Error

I’ve tried these snippets to no avail:

Columns(5).NumberFormat = "0"

and

 Selection.PasteSpecial Paste:=xlPasteValues, Operation:=xlNone, SkipBlanks _
        :=False, Transpose:=False

Teamothy's user avatar

Teamothy

1,9903 gold badges15 silver badges24 bronze badges

asked Apr 21, 2016 at 13:41

aLearningLady's user avatar

aLearningLadyaLearningLady

1,9384 gold badges20 silver badges42 bronze badges

4

Use the below function (changing [E:E] to the appropriate range for your needs) to circumvent this issue (or change to any other format such as «mm/dd/yyyy»):

[E:E].Select
With Selection
    .NumberFormat = "General"
    .Value = .Value
End With

P.S. In my experience, this VBA solution works SIGNIFICANTLY faster on large data sets and is less likely to crash Excel than using the ‘warning box’ method.

answered Apr 21, 2016 at 13:41

aLearningLady's user avatar

aLearningLadyaLearningLady

1,9384 gold badges20 silver badges42 bronze badges

3

I had this problem earlier and this was my solution.

With Worksheets("Sheet1").Columns(5)
    .NumberFormat = "0"
    .Value = .Value
End With

answered Apr 21, 2016 at 15:20

BerticusMaximus's user avatar

0

This can be used to find all the numeric values (even those formatted as text) in a sheet and convert them to single (CSng function).

For Each r In Sheets("Sheet1").UsedRange.SpecialCells(xlCellTypeConstants)
    If IsNumeric(r) Then
       r.Value = CSng(r.Value)
       r.NumberFormat = "0.00"
    End If
Next

answered Sep 2, 2017 at 21:29

Jones's user avatar

JonesJones

1812 silver badges4 bronze badges

1

This converts all text in columns of an Excel Workbook to numbers.

Sub ConvertTextToNumbers()
Dim wBook As Workbook
Dim LastRow As Long, LastCol As Long
Dim Rangetemp As Range

'Enter here the path of your workbook
Set wBook = Workbooks.Open("yourWorkbook")
LastRow = Cells.Find(What:="*", After:=Range("A1"), SearchOrder:=xlByRows, SearchDirection:=xlPrevious).Row
LastCol = Cells.Find(What:="*", After:=Range("A1"), SearchOrder:=xlByColumns, SearchDirection:=xlPrevious).Column

For c = 1 To LastCol
Set Rangetemp = Cells(c).EntireColumn
Rangetemp.TextToColumns DataType:=xlDelimited, _
    TextQualifier:=xlDoubleQuote, ConsecutiveDelimiter:=False, Tab:=True, _
    Semicolon:=False, Comma:=False, Space:=False, Other:=False, FieldInfo _
    :=Array(1, 1), TrailingMinusNumbers:=True
Next c
End Sub

answered Jan 11, 2017 at 15:39

ConertVBA's user avatar

1

''Convert text to Number with ZERO Digits and Number convert ZERO Digits  

Sub ZERO_DIGIT()
 On Error Resume Next
 Dim rSelection As Range
 Set rSelection = rSelection
 rSelection.Select
 With Selection
  Selection.NumberFormat = "General"
  .Value = .Value
 End With
 rSelection.Select
  Selection.NumberFormat = "0"
 Set rSelection = Nothing
End Sub

''Convert text to Number with TWO Digits and Number convert TWO Digits  

Sub TWO_DIGIT()
 On Error Resume Next
 Dim rSelection As Range
 Set rSelection = rSelection
 rSelection.Select
 With Selection
  Selection.NumberFormat = "General"
  .Value = .Value
 End With
 rSelection.Select
  Selection.NumberFormat = "0.00"
 Set rSelection = Nothing
End Sub

''Convert text to Number with SIX Digits and Number convert SIX Digits  


Sub SIX_DIGIT()
 On Error Resume Next
 Dim rSelection As Range
 Set rSelection = rSelection
 rSelection.Select
 With Selection
  Selection.NumberFormat = "General"
  .Value = .Value
 End With
 rSelection.Select
  Selection.NumberFormat = "0.000000"
 Set rSelection = Nothing
End Sub



answered Mar 14, 2020 at 9:10

Mahesh S's user avatar

0

The solution that for me works is:

For Each xCell In Selection

  xCell.Value = CDec(xCell.Value)

Next xCell 

answered Feb 22, 2018 at 17:56

Camilo Vargas's user avatar

Using aLearningLady’s answer above, you can make your selection range dynamic by looking for the last row with data in it instead of just selecting the entire column.

The below code worked for me.

Dim lastrow as Integer

lastrow = Cells(Rows.Count, 2).End(xlUp).Row

Range("C2:C" & lastrow).Select
With Selection
    .NumberFormat = "General"
    .Value = .Value
End With

answered Feb 10, 2019 at 18:18

Mikey's user avatar

MikeyMikey

701 gold badge1 silver badge10 bronze badges

The solution that worked for me many times is:

Sub ConvertTextToNumber()

With Range("A1:CX500") 'you can change the range 
.NumberFormat = "General"
.Value = .Value 
End With

End Sub

answered Sep 23, 2021 at 19:03

Hakob TARPOSHYAN's user avatar

For large datasets a faster solution is required.

Making use of ‘Text to Columns’ functionality provides a fast solution.

Example based on column F, starting range at 25 to LastRow

Sub ConvTxt2Nr()

Dim SelectR As Range
Dim sht As Worksheet
Dim LastRow As Long

Set sht = ThisWorkbook.Sheets("DumpDB")

LastRow = sht.Cells(sht.Rows.Count, "F").End(xlUp).Row

Set SelectR = ThisWorkbook.Sheets("DumpDB").Range("F25:F" & LastRow)

SelectR.TextToColumns Destination:=Range("F25"), DataType:=xlDelimited, _
    TextQualifier:=xlDoubleQuote, ConsecutiveDelimiter:=False, Tab:=True, _
    Semicolon:=False, Comma:=False, Space:=False, Other:=False, FieldInfo _
    :=Array(1, 1), TrailingMinusNumbers:=True

End Sub

answered Jan 15, 2019 at 7:07

Louis's user avatar

LouisLouis

392 bronze badges

1

From the recorded macro one gets the code below; for a new application you just need to update selection and range:

Sub num()

Columns("B:B").Select
Selection.TextToColumns Destination:=Range("B1"), DataType:=xlDelimited, _
    TextQualifier:=xlDoubleQuote, ConsecutiveDelimiter:=False, Tab:=True, _
    Semicolon:=False, Comma:=False, Space:=False, Other:=False, FieldInfo _
    :=Array(1, 1), TrailingMinusNumbers:=True
End Sub

L.Dutch's user avatar

L.Dutch

9263 gold badges17 silver badges38 bronze badges

answered Dec 14, 2022 at 14:59

A Albuquerque's user avatar

I had problems making above codes work. To me multiplying with 1 did the trick:-)

    Cells(1, 1).Select
    Cells(1, 1) = ActiveCell * 1 

answered Dec 23, 2021 at 12:13

Jacob Hald's user avatar

In a recent task, I was doing filter through VBA on a number column. But that number column had numbers in text format. When I run the VBA script, it didn’t work of course, because the filter was a number and the column had numbers as text. In that case, I needed to convert the text into numbers manually and save it. Then the macro worked perfectly. But I wanted to convert these texts into numbers using the VBA script and I was able to do it. I wanted to share this as if anyone wanted to know how to convert text values into a number using VBA, they can have a look at it.

Convert text to number using Range.NumberFormat method

This first and easiest method. I prefer this method over other methods as it directly converts the selected excel range into number format.

So, if you have a fixed range that you want to convert to text then use this VBA snippet.

Sub ConvertTextToNumber()
 Range("A3:A8").NumberFormat = "General"
 Range("A3:A8").Value = Range("A3:A8").Value
End Sub

When you run the above code it converts the text of range A3:A8 into text.

This code can look more elegant if we write it like this.

Sub ConvertTextToNumber()
 
 With Range("A3:A8")
  .NumberFormat = "General"
  .Value = .Value
 End With

End Sub

How does it work?

Well, it is quite simple. We first change the number format of the range to General. Then we put the value of that range into the same range using VBA. This removes the text formatting completely. Simple, isn’t it?

Change the number of formatting of a dynamic range

In the above code, we changed the text to number in the above code of a fixed range but this will not be the case most of the time. To convert text to a number of dynamic ranges, we can evaluate the last used cell or select the range dynamically.

This is how it would look:

Sub ConvertTextToNumber()
With Range("A3:A" & Cells(Rows.Count, 1).End(xlUp).Row)
.NumberFormat = "General"
 .Value = .Value
End With

Here, I know that the range starts from A3. But I don’t know where it may end.
So I dynamically identify last used excel row that has data in it using the VBA snippet Cells(Rows.Count, 1).End(xlUp).Row. It returns the last used row number that we are concatenating with «A3:A».

Note: This VBA snippet will work on the active workbook and active worksheet. If your code switches through multiple sheets, it would be better to set a range object of the intended worksheet. Like this

Sub ConvertTextToNumber()
 Set Rng = ThisWorkbook.Sheets("Sheet1").Range("A3:A" & Cells(Rows.Count, 1).End(xlUp).Row)
 With Rng
  .NumberFormat = "General"
  .Value = .Value
 End With
End Sub

The above code will always change the text to the number of the sheet1 of the workbook that contains this code.

Loop and CSng to change the text to number

Another method is to loop through each cell and change the cell value to a number using CSng function. Here’s the code.

Sub ConvertTextToNumberLoop()
 Set Rng = ThisWorkbook.Sheets("Sheet1").Range("A3:A" & Cells(Rows.Count, 1).End(xlUp).Row)
 
 For Each cel In Rng.Cells
    cel.Value = CSng(cel.Value)
 Next cel

End Sub

In the above VBA snippet, we are using VBA For loop to iterate over each cell in the range and convert the value of each cell into a number using the CSng function of VBA.

So yeah guys, this is how you can change texts to numbers in Excel using VBA. You can use these snippets to ready your worksheet before you do any number operation on them. I hope I was explanatory enough. You can download the working file here.

Change Text to Number Using VBA.

If you have any doubts regarding this text to number conversion or any other excel/VBA related query, ask in the comments section below.

Related Articles:

How to get Text & Number in Reverse through VBA in Microsoft Excel | To reverse number and text we use loops and mid function in VBA. 1234 will be converted to 4321, «you» will be converted to «uoy». Here’s the snippet.

Format data with custom number formats using VBA in Microsoft Excel | To change the number format of specific columns in excel use this VBA snippet. It coverts the number format of specified to specified format in one click.

Popular Articles:

50 Excel Shortcuts to Increase Your Productivity | Get faster at your task. These 50 shortcuts will make you work even faster on Excel.

The VLOOKUP Function in Excel | This is one of the most used and popular functions of excel that is used to lookup value from different ranges and sheets. 

COUNTIF in Excel 2016 | Count values with conditions using this amazing function. You don’t need filter your data to count specific value. Countif function is essential to prepare your dashboard.

How to Use SUMIF Function in Excel | This is another dashboard essential function. This helps you sum up values on specific conditions.

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

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

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

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

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

Sub Primer1()

    Debug.Print 23.1254 * 5.2  ‘Результат: 120,25208

    Debug.Print «23,1254» * «5,2» ‘Результат: 120,25208

    Debug.Print TypeName(«23,1254») ‘Результат: String

    Debug.Print TypeName(CDbl(«23,1254»)) ‘Результат: Double

End Sub

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

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

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

Sub Primer2()

    Debug.Print Val(«021.36abcde»)  ‘Результат: 21,36

    Debug.Print Format(Val(«021.36abcde»), «000.0»)  ‘Результат: 021,4

End Sub

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

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

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

Sub Primer3()

Dim MyCell As Range

    Selection.NumberFormat = «General»

        For Each MyCell In Selection

            If IsNumeric(MyCell) Then MyCell = MyCell * 1

        Next

End Sub

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


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!

METHOD 1. Convert text to numbers with specific range using VBA

VBA

Sub Convert_Text_to_Numbers()

Dim ws As Worksheet

Set ws = Worksheets(«Analysis»)

With ws.Range(«B5»)

.NumberFormat = «General»
.Value = .Value

End With

End Sub

OBJECTS
Worksheets: The Worksheets object represents all of the worksheets in a workbook, excluding chart sheets.
Range: The Range object is a representation of a single cell or a range of cells in a worksheet.

PREREQUISITES
Worksheet Name: Have a worksheet named Analysis.
Range: In this example we are converting the text in cell («B5») to a number. Therefore, if using the exact VBA code, you need to capture the text that you want to convert to a number in cell («B5»).

ADJUSTABLE PARAMETERS
Range: Select the range that captures the text that you want to convert to a number by changing the cell reference («B5») in the VBA code to any range in the worksheet, that doesn’t conflict with the formula.
Worksheet Name: Select the worksheet where you are converting text to a number by changing the worksheet name («Analysis») in the VBA code to any existing worksheet in the workbook, that doesn’t conflict with the formula.

ADDITIONAL NOTES
Note 1: This VBA code will convert the text to a number in the same cell that the text is captured. In this example it will be cell («B5»).

METHOD 2. Convert text to numbers of selected range using VBA

VBA

Sub Convert_Text_to_Numbers()

With Selection

.NumberFormat = «General»
.Value = .Value

End With

End Sub

ADDITIONAL NOTES
Note 1: This VBA code will convert the text to a number in the selected cell.

METHOD 3. Convert text to numbers with specific range and different output range using VBA

VBA

Sub Convert_Text_to_Numbers()

Dim ws As Worksheet

Set ws = Worksheets(«Analysis»)

ws.Range(«D5») = ws.Range(«B5»)

With ws.Range(«D5»)

.NumberFormat = «General»
.Value = .Value

End With

End Sub

OBJECTS
Worksheets: The Worksheets object represents all of the worksheets in a workbook, excluding chart sheets.
Range: The Range object is a representation of a single cell or a range of cells in a worksheet.

PREREQUISITES
Worksheet Name: Have a worksheet named Analysis.
Range: In this example we are converting the text in cell («B5») to a number. Therefore, if using the exact VBA code, you need to capture the text that you want to convert to a number in cell («B5»).

ADJUSTABLE PARAMETERS
Range: Select the range that captures the text that you want to convert to a number by changing the cell reference («B5») in the VBA code to any range in the worksheet, that doesn’t conflict with the formula.
Range: Select the output range by changing the cell reference («D5») in the VBA code to any range in the worksheet, that doesn’t conflict with the formula.
Worksheet Name: Select the worksheet where you are converting text to a number by changing the worksheet name («Analysis») in the VBA code to any existing worksheet in the workbook, that doesn’t conflict with the formula.

METHOD 4. Convert text to numbers with specific range and different output range (with For Loop) using VBA

VBA

Sub Convert_Text_to_Numbers()

Dim ws As Worksheet

Set ws = Worksheets(«Analysis»)

For x = 5 To 10

ws.Range(«D» & x) = ws.Range(«B» & x)

With ws.Range(«D» & x)

.NumberFormat = «General»
.Value = .Value

End With

Next

End Sub

OBJECTS
Worksheets: The Worksheets object represents all of the worksheets in a workbook, excluding chart sheets.
Range: The Range object is a representation of a single cell or a range of cells in a worksheet.

PREREQUISITES
Worksheet Name: Have a worksheet named Analysis.
Range: In this example we are converting the text in range («B5:B10») to numbers. Therefore, if using the exact VBA code, you need to capture the text that you want to convert to numbers in range («B5:B10»).

ADJUSTABLE PARAMETERS
Output and Text Row Range: The text and output range in the same rows (row 5 to 10), which are represented by the x variable. You can select the output row range by changing the x For and To values in the VBA code.
Output and Text Column Range: Select the column text and output range by changing the column reference («B») and («D»), respectively, in the VBA code.
Worksheet Name: Select the worksheet where you are converting text to a number by changing the worksheet name («Analysis») in the VBA code to any existing worksheet in the workbook, that doesn’t conflict with the formula.

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

VBA Convert Number Stored As Text To Number. Here the input value is number stored as number but in string format, we are converting this value as number. In the following article let us see an example. And also see the step by step instructions to run VBA code in the visual basic editor(VBE) window.

Convert Number Stored As Text To Number

Let us see an example VBA macro code how to Convert a range of Numbers Stored As Text To Numbers.

'Convert Number stored as text to Number
Sub VBAF1_Convert_Number_Stored_as_Text_to_Number()
    
    'Variable declaration
    Dim rngRange As Range
    
   'Define Range which you want to convert to range
    Set rngRange = ActiveSheet.Range("A1:A20")
    
    'Convert Number
    rngRange.Value = rngRange.Value
   
End Sub

Explanation: You can change defined range as per your requirement. When dealing with huge data we can use above specified process to convert numbers to numbers which are stored as text. We can also loop through each cell, but it takes longer time to execute. Please find below screen shot for your reference.

VBA Convert Numbers Stored As Text To Numbers

VBA Convert Numbers Stored As Text To Numbers

Instructions to Run VBA Macro Code or Procedure:

You can refer the following link for the step by step instructions.

Instructions to run VBA Macro Code

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 VBA Text Files VBA Tables

VBA Editor Keyboard Shortcut Keys List VBA Interview Questions & Answers Blog

Содержание

  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» ). Но текстовые значения в ячейках еще не преобразовались в числа. Обходим циклом все ячейки диапазона, и, если текстовое значение ячейки можно интерпретировать как число, умножаем это значение на единицу. После этого текст будет преобразован в число.

Источник

Sometimes you get a dataset that has numbers stored as text. This means you cannot work with the values as you would with actual numbers.

If you try to, they give unexpected results. For example, if you sum them, you get a 0 (zero) regardless of the values involved. This tutorial shows how to convert numbers stored as text to actual numbers using Excel VBA.

How to Identify Numbers Stored as Text

Sometimes Excel fails to convert numeric values to number format and stores them as text as in the example dataset below:

The values in the dataset are left-aligned meaning Excel treats them as text values.

When you select any cell in the dataset a yellow triangle with an exclamation point pops up beside it:

Table

Description automatically generated with medium confidence

When you hover over the yellow triangle, you see the message “The number in this cell is formatted as text or preceded by an apostrophe.”

Graphical user interface, application, table, Excel

Description automatically generated

3 Methods to Convert Text to Number Using Excel VBA

There are several ways we can use to convert numbers stored as text to number format in Excel. This tutorial focuses on converting using Excel VBA. We shall use copies of the example dataset in our illustrations.

Method 1: Use the Excel VBA Range.NumberFormat Property

The Range.NumberFormat property returns or sets a Variant value that represents the format code for the object.

We use the following steps:

  1. In the active worksheet that contains the dataset, press Alt + F11 to open the Visual Basic Editor (VBE).
  2. Click Insert >> Module to insert a new module.

  1. Type the following procedure in the module and remember to change the range to your range:

Sub convertTextToNumber()

    With Range(«A2:A15»)

        .NumberFormat = «General»

        .Value = .Value

    End With

End Sub

  1. Save the procedure and save the workbook as a macro-enabled workbook.
  2. Place the cursor anywhere in the procedure and press F5 to run the code.
  3. Press Alt + F11 to switch back to the active worksheet to see the results of the procedure.

Table

Description automatically generated with low confidence

The values in the data range are now right-aligned because they have been converted to number format.

  1. Close the Visual Basic Editor.

Explanation of the procedure

Sub convertTextToNumber()

    With Range(«A2:A15»)

        .NumberFormat = «General»

        .Value = .Value

    End With

End Sub

  • The With statement is used with the mentioned range to minimize the code.
  • NumberFormat = “General”. The General number format is assigned to the values in the mentioned range.
  • Value = Value. The values that have been converted to the General number format are assigned to the cells in the range.

Method 2: Use Excel VBA Loop and CSng function

In this method, the procedure loops through the dataset and converts the values to single-precision numbers using the CSng function.

We use the following steps:

  1. In the active worksheet that contains the dataset press Alt + F11 to open the Visual Basic Editor.
  2. Click Insert >> Module to insert a new module.
  3. Type the following procedure in the new module:

Sub convertTextToNumber2()

Dim r As Variant

    For Each r In Sheets(«Method 2»).UsedRange.SpecialCells(xlCellTypeConstants)

        If IsNumeric(r) Then

            r.Value = CSng(r.Value)

            r.NumberFormat = «General»

        End If

    Next

End Sub

  1. Save the procedure and save the workbook as a macro-enabled workbook.
  2. Place the cursor anywhere in the procedure and press F5 to run the procedure.
  3. Press Alt + F11 to switch back to the active worksheet to see the results of the procedure.

The values in the data range are now right-aligned because they have been converted to number format.

  1. Close the Visual Basic Editor.

Explanation of the code

Sub convertTextToNumber2()

Dim r As Variant

    For Each r In Sheets(«Method 2»).UsedRange.SpecialCells(xlCellTypeConstants)

        If IsNumeric(r) Then

            r.Value = CSng(r.Value)

            r.NumberFormat = «General»

        End If

    Next

End Sub

  • The variable called r of type Variant is declared. The Variant data type can contain any type of data except the fixed-length String data. It is appropriate because the variable will first contain text values and then the converted numeric values.
  • For Each Loop goes through each cell that contains a constant (a value that is directly inserted into a cell) in the used range of the mentioned worksheet and does the following:
  • Checks if it is a number using the IsNumeric function. If it is a number, it turns it to single precision using the CSng function and assigns the General number format to it.

Method 3: Convert Text to Number in a Dynamic Range

In the previous methods, we worked with selected ranges.

In this method, we work with a dynamic range.

We use the following steps:

  1. In the active worksheet that contains the dataset press Alt + F11 to open the Visual Basic Editor.
  2. Click Insert >> Module to insert a new module.
  3. Type the following procedure in the new module:

Sub ConvertTextToNumber3()

    With Range(«A2:A» & Cells(Rows.Count, «A»).End(xlUp).Row)

        .NumberFormat = «General»

        .Value = .Value

    End With

End Sub

  1. Save the procedure and save the workbook as a macro-enabled workbook.
  2. Place the cursor anywhere in the procedure and press F5 to run the code.
  3. Press Alt + F11 to switch back to the active workbook to see the results of the procedure.

The values in the data range are now right-aligned because they have been converted to number format.

  1. Close the Visual Basic Editor.

Explanation of the procedure

Sub ConvertTextToNumber3()

    With Range(«A2:A» & Cells(Rows.Count, «A»).End(xlUp).Row)

        .NumberFormat = «General»

        .Value = .Value

    End With

End Sub

  • The With statement is used with the mentioned range to minimize the code.
  • “A2:A” & Cells(Rows.Count, “A”).End(xlUp).Row. The number of the last nonblank row in column A is dynamically identified by Cells(Rows.Count, “A”).End(xlUp).Row. That number is concatenated with “A2:A” to identify the range.
  • NumberFormat = “General”. The number format of the range is set to General.
  • Value = Value. The values that are now in General number format are assigned to the cells in the range.

Conclusion

If you get a dataset that has numbers that are stored as text, you cannot work with the values as you would with numbers. For example, if you try to sum them, you get a 0 (zero) regardless of the values involved. This tutorial explained how to convert such data range from text format to number format using Excel VBA.

Ezoic

Post Views: 560

Понравилась статья? Поделить с друзьями:
  • Vba excel text in cell no
  • Vba excel shapes group
  • Vba excel shape свойства
  • Vba excel shape no fill
  • Vba excel set sheet