To convert a value to a number in VBA, use a conversion function such as CLng, CDbl, or CDec when you know the required numeric type; use IsNumeric first when the input may be invalid. For a worksheet range, convert each cell’s value and handle errors or blanks before writing the result back. The right method depends on whether you need a whole number, a decimal, or Excel’s general numeric value.
What You’ll Need
- Microsoft Excel for Microsoft 365 on Windows, with a workbook that can contain macros.
- A value or range to convert, and a decision about whether decimals should be kept or rounded.
- Permission to run macros. Save a copy of the workbook before running any macro: VBA changes cannot be undone with Ctrl+Z.
To open the Visual Basic Editor on Windows, press Alt+F11. If the Developer tab is not visible, enable it through File > Options > Customize Ribbon, then check Developer. On a Mac, open the editor with Option+F11 (some keyboards require Fn as well), or use Tools > Macro > Visual Basic Editor. Macro security and available menu wording can vary by Excel version.
Step-by-Step
- Choose the numeric type. Use
CIntfor a 16-bit integer,CLngfor a 32-bit whole number,CSngfor a single-precision decimal,CDblfor a double-precision decimal, orCDecfor a Decimal value stored in a Variant. VBA’sIntegertype is limited to -32,768 through 32,767, soLongis usually the safer choice for whole-number counts.Valis another option for simple text, but it parses only up to the first unrecognized character and does not follow regional decimal separators as reliably as the conversion functions. - Create a test macro. In the Visual Basic Editor, choose Insert > Module. Add this example, which checks a text value and converts it to a Long before using it:
Option Explicit
Sub ConvertTextToNumber()
Dim rawValue As Variant
Dim convertedValue As Long
rawValue = "125"
If IsNumeric(rawValue) Then
convertedValue = CLng(rawValue)
MsgBox "Converted value: " & convertedValue
Else
MsgBox "The input is not a valid number."
End If
End Sub
- Run the macro on the test value. Put the cursor inside
ConvertTextToNumberand pressF5, or return to Excel and choose Developer > Macros, select the macro, and click Run. The message should show 125. On Mac, use the editor’s Run command or the Macros dialog; keyboard shortcuts can differ by keyboard and settings. - Use the function that matches the data. For a decimal such as
"12.75", useCDblif you need to retain fractional precision.CIntandCLngdo not simply discard the fraction: they round to the nearest integer, with midpoint values rounded to the nearest even integer. If you specifically need to remove the fractional part, useFix(toward zero) orInt(toward negative infinity), then assign the result to a suitable whole-number variable. - Convert a worksheet cell safely. This macro reads A2, checks for an Excel error and blank content, validates the value, and writes a Double to B2. Change the sheet and cell references to suit your workbook:
Option Explicit
Sub ConvertCellToNumber()
Dim sourceCell As Range
Dim outputCell As Range
Dim rawValue As Variant
Dim convertedValue As Double
Set sourceCell = ThisWorkbook.Worksheets("Sheet1").Range("A2")
Set outputCell = ThisWorkbook.Worksheets("Sheet1").Range("B2")
rawValue = sourceCell.Value2
If IsError(rawValue) Then
outputCell.Value = "Source contains an error"
ElseIf Len(Trim$(CStr(rawValue))) = 0 Then
outputCell.ClearContents
ElseIf IsNumeric(rawValue) Then
convertedValue = CDbl(rawValue)
outputCell.Value = convertedValue
Else
outputCell.Value = "Not numeric"
End If
End Sub
- Adapt it for a range, then verify the output. Put a loop around the cell logic to process rows from a chosen starting row to the last populated row. Decide what the macro should do with blanks and invalid entries—skip them, flag them, or stop with a message. Test on a small copied range first. Check that converted values calculate as numbers, and apply an appropriate number format using Home > Number if you want a particular display.
- Save and run carefully. Save macro-enabled workbooks as
.xlsmif you need to retain VBA. Review the selected worksheet and destination cells before running the procedure. A macro may overwrite existing values, and Ctrl+Z will not reverse its changes.
Common Mistakes
- Picking a type that is too small.
CIntcan overflow above 32,767. UseCLngfor larger whole numbers, orCDblwhen a decimal is needed. VBA’sLongLongis available only in 64-bit VBA; avoid it if the code must also run in 32-bit Excel. - Assuming a conversion function validates input. A direct call such as
CDbl(rawValue)raises a run-time error for text that cannot be converted. UseIsNumericand, where relevant,IsErrorbefore conversion. - Confusing rounding with truncation. Converting a decimal to an integer rounds; it does not always drop everything after the decimal point. Choose
FixorIntwhen truncation or floor behavior is required. - Ignoring regional settings. Text such as
"1,25"may mean different things in different locales. Conversion functions interpret numeric text using the system’s regional conventions. Do not remove commas or periods blindly; first establish whether they are decimal or thousands separators. - Overwriting the source unintentionally. Keep the original values in a separate column until the results have been checked. A macro cannot be reversed with Excel’s Undo command.
Tips
- Use
Value2when reading worksheet cells for numeric processing. It returns the underlying value without the Currency and Date subtypes that can be returned byValue. - Use
Option Explicitat the top of modules. It requires variable declarations and helps catch misspelled names before a macro runs. - Use
IsNumericas a practical check, not a guarantee that every possible input can be safely converted to every numeric type. The chosen type can still overflow, so handle errors when inputs are uncontrolled. - Keep identifiers such as ZIP codes, phone numbers, and account numbers as text when leading zeros or exact digit sequences matter. A numeric conversion can remove leading zeros, and floating-point types cannot represent every very long integer exactly.
- For large ranges, read cells into a Variant array, convert in memory, and write the array back in one operation. This is generally faster than interacting with the worksheet cell by cell, but carefully preserve blanks and invalid values.
Troubleshooting
Type mismatch: Inspect the source value in the Immediate window or display it with MsgBox CStr(rawValue). Check for spaces, nonbreaking spaces, currency symbols, error values, or text that uses a different decimal separator. Trim ordinary spaces and validate before converting; do not strip characters unless you know they are safe to remove.
Overflow: The value exceeds the selected type’s range. Change CInt to CLng for a larger whole number, or use CDbl for a decimal, while considering precision requirements. A Double is not exact for every very large integer.
The output still looks like text: Confirm that the macro writes the converted variable, not the original text, and that the destination cell is not being populated by a later formula or process. A number format changes appearance, not the underlying value. Test the result with IsNumeric(outputCell.Value2) or use it in a calculation.
Macro will not run: Confirm the file is saved as .xlsm, the procedure is in a standard module, and macros are permitted by your organization’s security settings. Do not enable macros in files from untrusted sources.
Frequently Asked Questions
What is the simplest way to convert text to a number in VBA?
Use the appropriate conversion function, such as CLng for a whole number or CDbl for a decimal. Validate uncertain input with IsNumeric first.
What is the difference between Val and CDbl?Val reads a numeric prefix and stops at the first character it does not recognize; for example, it can treat "12abc" as 12. CDbl converts a value using regional numeric conventions and raises an error when the input is invalid.
Does CInt remove decimal places?
No. CInt rounds to the nearest integer, using banker’s rounding for midpoint values, and can overflow outside the Integer range. Use Fix for truncation toward zero.
How do I convert a whole column?
Loop over the used rows, validate each cell, and write results to a separate column. Test the loop on a copy first, and explicitly decide how to treat blanks, errors, and nonnumeric text.
Can I convert numbers stored as text without VBA?
Often, yes: use Excel’s VALUE function in a worksheet formula or use Data > Text to Columns when appropriate. VBA is useful when the conversion must be repeated or applied as part of a larger task.
Related
- Excel Convert Percentage Text to Number
- How to Convert Exponential to Number in Excel: A Guide
- Convert Hours to a Number in Excel: Time to Decimal
Try it: the Column Letter to Number: aA is 27, XFD is 16,384. Converts both ways.
More in VBA & macros
- VBA Check If Workbook Exists: Paths, Files, and ErrorsYes. In VBA, use Dir$ with the workbook’s full file path and check whether it returns an empty…
- How to Turn On Excel’s Macro Recorder in Microsoft 365In Excel for Microsoft 365 on Windows, select Developer > Code > Record Macro, set the macro’s name…
- How to Open Visual Basic in Excel Using the VBA EditorIn Excel for Microsoft 365 on Windows, press Alt+F11 to open the Visual Basic Editor, or select Developer…
- VBA AutoFilter Exclude Criteria: How to Filter Out ValuesTo exclude a value with VBA AutoFilter, use a not-equal criterion such as <>Closed: filterRange.AutoFilter Field:=3, Criteria1:="<>Closed". The…
- Replace Excel Macros? Alternatives and When to SwitchYes—many Excel macros can be replaced, but the right substitute depends on the task: use formulas for calculations,…
- Excel Macro Error? Common Causes and FixesAn Excel macro error usually means VBA is blocked, the code cannot find an expected workbook, worksheet, or…
Sources: Function behaviour and menu paths: Microsoft Support documentation for Excel. Method & sources
Spotted an error in this guide? Let us know.