Convert Range to Numbers

Lately I've been working with a spreadsheet that imports data from a database application (Access). The numbers are formatted as text because some of them contain letters. So the whole field has to be formatted as text. :roll:

Then again, I'm not sure if the text formatting is because of that, or if it's just a function of being a foreign data source.

Anyway, I squeezed out this code (based on Trimming cells, before and after) that takes numeric cells and converts them to numbers. You need to select the data first.

Sub ConvertToNumber()

Dim arrData() As Variant
Dim arrReturnData() As Variant
Dim rng As Excel.range
Dim lRows As Long
Dim lCols As Long
Dim i As Long, j As Long

  lRows = Selection.rows.count
  lCols = Selection.Columns.count

  ReDim arrData(1 To lRows, 1 To lCols)
  ReDim arrReturnData(1 To lRows, 1 To lCols)

  ' read the selected range into an array
  Set rng = Selection
  arrData = rng.value

  ' set the number format
  rng.NumberFormat = "0"

  ' loop through array
  For j = 1 To lCols
    For i = 1 To lRows
      If IsNumeric(arrData(i, j)) Then ' convert to number
        arrReturnData(i, j) = CLng(arrData(i, j))
      Else ' leave it alone
        arrReturnData(i, j) = arrData(i, j)
      End If
    Next i
  Next j

  rng.value = arrReturnData

End Sub

I'm also aware that I could have done a "Copy / Paste Special" on the selection as well.

About JP

I'm just an average guy who writes VBA code for a living. This is my personal blog. Excel and Outlook are my thing, with a sprinkle of Access and Word here and there. Follow this space to learn more about VBA. Keep Reading »

Share This Article:

Share and bookmark this articledelicious buttonfacebook buttonlinkedin buttonstumbleupon buttontwitter button

Related Articles:



comment bubble 5 Comments on Convert Range to Numbers:

  1. Khushnood Viccaji writes:

    "If IsNumeric(arrData(i, j)) Then ' convert to number"

    Shouldn't this line be :
    "If NOT IsNumeric(arrData(i, j)) Then ' convert to number" ?

    • Khushnood Viccaji writes:

      Unless, you're forcibly converting ANY IsNumeric = TRUE cell to a Number; .
      And other (non-numeric) cells are left untouched ?

      My mistake in that case… apologies !

      • JP writes:

        That's correct, if the cell contents can be evaluated as a number, we convert it to a number. Otherwise if the cell contains text (as some of mine do), it is left alone.

  2. Gregory writes:

    This looks good but when it encounters a blank cell it will return a zero. I would change one line to fix this.

    If IsNumeric(arrData(i, j)) And Not IsEmpty(arrData(i, j)) Then ' convert to number if not empty
    
  3. Rick Rothstein (MVP - Excel) writes:

    IsNumeric may not be the best function to use to determine if an entry is a number or not. Try using your ConvertToNumber macro on these values and tell me if the results are what you would expect (the last 4 will need to have the cells formatted as Text before you enter them)….

    &7
    &o1
    &Head
    $0$
    1,2,3,4,5
    1,,2,,3,,4
    $(1,,2,,3,,)$
    456-
    1D2
    3E4
    123+
    (123)

    Here is a message that I started posting a long time ago in the old "compiled VB" newsgroups (where it dealt with TextBox entries) and more recently in the Excel newsgroups/forums when the need arose (the message describes the problem and a coding alternative to IsNumeric)…

    I usually try and steer people away from using IsNumeric to "proof" supposedly numeric text. Consider this (also see note below):

    ReturnValue = IsNumeric("($1,23,,3.4,,,5,,E67$)")

    Most people would not expect THAT to return True. IsNumeric has some "flaws" in what it considers a proper number and what most programmers are looking for.

    I had a short tip published by Pinnacle Publishing in their Visual Basic Developer magazine that covered some of these flaws. Originally, the tip was free to view but is now viewable only by subscribers.. Basically, it said that IsNumeric returned True for things like — currency symbols being located in front or in back of the number as shown in my example (also applies to plus, minus and blanks too); numbers surrounded by parentheses as shown in my example (some people use these to mark negative numbers); numbers containing any number of commas before a decimal point as shown in my example; numbers in scientific notation (a number followed by an upper or lower case "D" or "E", followed by a number equal to or less than 305 — the maximum power of 10 in VB); and Octal/Hexadecimal numbers (&H for Hexadecimal, &O or just & in front of the number for Octal).

    NOTE:
    ======
    In the above example and in the referenced tip, I refer to $ signs and commas and dots — these were meant to refer to your currency, thousands separator and decimal point symbols as defined in your local settings — substitute your local regional symbols for these if appropriate.

    As for your question about checking numbers, here are two functions that I have posted in the past for similar questions….. one is for digits only and the other is for "regular" numbers (the code is simple enough that it can be pulled from the function "housing" and used directly inside your own code):

         Function IsDigitsOnly(Value As String) As Boolean
             IsDigitsOnly = Len(Value) > 0 And _
                            Not Value Like "*[!0-9]*"
         End Function
    
         Function IsNumber(ByVal Value As String) As Boolean
             '   Leave the next statement out if you don't
             '   want to provide for plus/minus signs
             If Value Like "[+-]*" Then Value = Mid$(Value, 2)
             IsNumber = Not Value Like "*[!0-9.]*" And _
                               Not Value Like "*.*.*" And _
                               Len(Value) > 0 And Value <> "."
         End Function
    

    Here are revisions to the above functions that deal with the local settings for decimal points (and thousand's separators) that are different than used in the US (this code works in the US too, of course).

         Function IsNumber(ByVal Value As String) As Boolean
           Dim DP As String
           '   Get local setting for decimal point
           DP = Format$(0, ".")
           '   Leave the next statement out if you don't
           '   want to provide for plus/minus signs
           If Value Like "[+-]*" Then Value = Mid$(Value, 2)
           IsNumber = Not Value Like "*[!0-9" & DP & "]*" And _
                      Not Value Like "*" & DP & "*" & DP & "*" And _
                      Len(Value) > 0 And Value <> DP
         End Function
    

    I'm not as concerned by the rejection of entries that include one or more thousand's separators, but we can handle this if we don't insist on the thousand's separator being located in the correct positions (in other words, we'll allow the user to include them for their own purposes… we'll just tolerate their presence).

         Function IsNumber(ByVal Value As String) As Boolean
           Dim DP As String
           Dim TS As String
           '   Get local setting for decimal point
           DP = Format$(0, ".")
           '   Get local setting for thousand's separator
           '   and eliminate them. Remove the next two lines
           '   if you don't want your users being able to
           '   type in the thousands separator at all.
           TS = Mid$(Format$(1000, "#,###"), 2, 1)
           Value = Replace$(Value, TS, "")
           '   Leave the next statement out if you don't
           '   want to provide for plus/minus signs
           If Value Like "[+-]*" Then Value = Mid$(Value, 2)
           IsNumber = Not Value Like "*[!0-9" & DP & "]*" And _
                      Not Value Like "*" & DP & "*" & DP & "*" And _
                      Len(Value) > 0 And Value <> DP
         End Function
    
This article is closed to new comments. Why?
Peltier Tech Chart Utilities for Excel Peltier Tech Waterfall Chart Utility Peltier Tech Box and Whisker Chart Utility Peltier Tech Cluster-Stack Chart Utility Peltier Tech Panel Chart Utility Peltier Tech Marimekko Chart Utility Peltier Tech Dot Plot Utility Peltier Tech Cascade Chart Utility