Excel VBA Val Function: How to Convert Text to Numbers
In this article
The Excel VBA Val function is used to convert a string of text into a numeric value. It reads a string from left to right and stops as soon as it encounters a character that it does not recognize as part of a number, returning the numeric portion it found before that point. This is essential for cleaning data, handling user input from InputBoxes, or processing text files where numbers are mixed with non-numeric symbols.
What You'll Need
- Microsoft Excel installed on a Windows or Mac computer.
- Access to the Visual Basic for Applications (VBA) editor (typically accessed via the Developer tab).
- A basic understanding of how to create a Sub procedure or a User Defined Function (UDF).
Step-by-Step
- Open the VBA Editor: Launch Excel and press
Alt + F11on your keyboard. This opens the Visual Basic Editor window where all your macros and modules are stored. - Insert a New Module: In the top menu, go to
Insert > Module. This creates a blank space where you can write your code. Writing code in a module ensures your functions are available throughout the entire workbook. - Write a Simple Test Procedure: To see the Val function in action, type the following code into the module:
Sub TestValFunction() Dim myText As String Dim myNumber As Double myText = "123.45 ABC" myNumber = Val(myText) MsgBox "The numeric value is: " & myNumber End SubIn this example, the Val function looks at "123.45 ABC", identifies the digits and the decimal point, and stops once it hits the space before "ABC". - Run the Macro: Place your cursor anywhere inside the
Sub TestValFunction()block and pressF5or click the green "Run" arrow in the toolbar. A message box will appear showing123.45. - Handle User Input: The Val function is most useful when dealing with dynamic input. Try this more advanced version:
Sub GetUserAge() Dim userInput As String Dim age As Double userInput = InputBox("Please enter your age:") age = Val(userInput) If age = 0 And userInput <> "0" Then MsgBox "Invalid input. Please enter a number." Else MsgBox "Your age is recorded as " & age End If End SubHere, Val prevents the code from crashing (throwing a Type Mismatch error) if the user types "Twenty" instead of "20". - Apply Val to a Range of Cells: You can use Val to clean a column of "dirty" numeric data (e.g., cells containing "$50.00 USD"). Use a loop like this:
Sub CleanColumn() Dim cell As Range For Each cell In Selection cell.Value = Val(cell.Value) Next cell End SubSelect a range of cells in your sheet and run this macro to strip away trailing text and convert the results to numbers.
Common Mistakes
One of the most frequent mistakes is assuming the Val function handles regional settings for decimals. The Val function only recognizes the period (.) as a valid decimal separator. If you are in a region (such as France or Germany) where a comma (,) is used as the decimal separator, Val will stop reading the string the moment it hits that comma. For example, Val("12,34") will return 12, not 12.34. To handle regional decimals, you should use the CDbl function instead, though CDbl will throw an error if the string contains non-numeric characters, whereas Val will not.
Another common error is confusing Val with CInt or CLng. While these all result in numbers, CInt (Convert to Integer) and CLng (Convert to Long) are designed to convert a value that is already numeric or a string that is purely numeric. If you pass a string like "100 USD" to CInt, VBA will trigger a "Type Mismatch" error. Val is specifically designed to be "forgiving" and extract the number from the start of a string without crashing.
Users also often forget that Val returns a Double (a floating-point number). If you are assigning the result to an Integer variable, VBA will perform an implicit conversion, which may result in rounding. Always declare your receiving variable as Double if you expect decimal values.
Tips
To make your code more robust, combine Val with the Trim function. While Val ignores leading spaces, using Trim ensures that any accidental whitespace at the beginning or end of your string is removed before processing, which is a best practice for data cleaning.
If you need to extract a number that is not at the beginning of the string (e.g., "Order #12345"), the Val function will not work because it stops at the first non-numeric character (the "O" in Order). In these cases, you must first use a combination of Mid, InStr, or Regular Expressions to isolate the numeric part of the string before passing it to the Val function.
When dealing with currency, be aware that Val does not recognize currency symbols. Val("$100") will return 0 because the dollar sign is the first character and it is not a number. You must strip the symbol using Replace(" $100", "$", "") or Mid before applying Val.
Troubleshooting
If the Val function is returning 0 when you expect a number, check the very first character of your string. If the string starts with a letter, a space (in some specific contexts), or a currency symbol, Val will immediately stop and return 0. Use the Debug.Print command in the Immediate Window (Ctrl + G) to see exactly what the string looks like before it enters the Val function.
If you are seeing unexpected rounding (e.g., 12.5 becoming 13), check your variable declarations. If you declared your variable as Dim myNum As Integer, VBA will round the result of Val to the nearest whole number. Change the declaration to Dim myNum As Double to preserve the decimal precision.
If you are working in a non-US locale and the function is ignoring your decimals, stop using Val. Instead, use CDbl. To prevent CDbl from crashing on non-numeric text, wrap it in an IsNumeric check: If IsNumeric(myString) Then myNum = CDbl(myString). This provides the regional awareness that Val lacks while maintaining the stability of your macro.
Frequently Asked Questions
Does Val() handle scientific notation?
Yes, the Val function recognizes scientific notation. If you provide a string like "1e3", Val will correctly return 1000.
What happens if the string is empty?
If you pass an empty string ("") or a Null value to the Val function, it will return 0 without triggering an error.
Can Val() be used directly in an Excel cell formula?
No, Val is a VBA-specific function. To achieve similar results in a worksheet cell, you can use the VALUE function or a combination of LEFT, FIND, and VALUE.
Does Val() recognize commas as thousands separators?
No. Val treats the comma as a non-numeric character. For example, Val("1,200") will return 1 because it stops reading as soon as it encounters the comma.
Is Val() faster than CDbl()?
The performance difference is negligible for most users. The choice between them should be based on whether you need to handle non-numeric characters (use Val) or regional decimal settings (use CDbl).