Results 1 to 6 of 6

Thread: Solved: VBA: Extract Number from Cell

Hybrid View

Previous Post Previous Post   Next Post Next Post
  1. #1
    VBAX Regular
    Joined
    Jun 2007
    Posts
    58
    Location

    Solved: VBA: Extract Number from Cell

    Did a search but didn't get the exact results i was looking for.

    Here's my situation, i have a cell with multiple numbers in it. The numbers are separated by a comma, and sometimes there is a number range in the cell. So for example, one cell may contain 39,40,43,45-49. How do I extract the numbers? Also for 45-49, I want all the numbers in between i.e. 45 46 47 48 49.

    Any help is appreciated.

  2. #2
    Administrator
    VP-Knowledge Base
    VBAX Grand Master mdmackillop's Avatar
    Joined
    May 2004
    Location
    Scotland
    Posts
    14,489
    Location
    How do you want the result returned?
    MVP (Excel 2008-2010)

    Post a workbook with sample data and layout if you want a quicker solution.


    To help indent your macros try Smart Indent

    Please remember to mark threads 'Solved'

  3. #3
    Distinguished Lord of VBAX VBAX Grand Master Bob Phillips's Avatar
    Joined
    Apr 2005
    Posts
    25,455
    Location
    Quote Originally Posted by mdmackillop
    How do you want the result returned?
    I was just about to post the same question
    ____________________________________________
    Nihil simul inventum est et perfectum

    Abusus non tollit usum

    Last night I dreamed of a small consolation enjoyed only by the blind: Nobody knows the trouble I've not seen!
    James Thurber

  4. #4
    VBAX Regular
    Joined
    Jun 2007
    Posts
    58
    Location
    I want to store the results in an array.

  5. #5
    Administrator
    VP-Knowledge Base VBAX Grand Master mdmackillop's Avatar
    Joined
    May 2004
    Location
    Scotland
    Posts
    14,489
    Location
    [VBA]Option Explicit
    Sub Test()
    Dim rng As Range, Num
    Dim Result(), Arr, x, r
    Dim i As Long, j As Long, k As Long
    Dim msg As String



    ReDim Result(100)
    Set rng = Range("d5")
    Arr = Split(rng, ",")
    For i = 0 To UBound(Arr)
    Num = Arr(i)
    If InStr(1, Num, "-") = 0 Then
    Result(j) = Num
    j = j + 1
    Else
    x = Split(Num, "-")
    For k = x(0) To x(1)
    Result(j) = k
    j = j + 1
    Next
    End If
    Next
    ReDim Preserve Result(j - 1)

    For Each r In Result
    msg = msg & r & vbCr
    Next
    MsgBox msg
    End Sub[/VBA]
    MVP (Excel 2008-2010)

    Post a workbook with sample data and layout if you want a quicker solution.


    To help indent your macros try Smart Indent

    Please remember to mark threads 'Solved'

  6. #6
    VBAX Regular
    Joined
    Jun 2007
    Posts
    58
    Location
    That worked! Thanks!

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •