Quantcast
Channel: Active questions tagged excel - Stack Overflow
Viewing all articles
Browse latest Browse all 88066

Excel: How to list the numbers of a sequence of intervals?

$
0
0

I was looking for a way to do what the title says and just found the follow thread: Excel: Listing Numbers In Between 2 Numbers

But my case is a little different: there is a cell where will be typed some integer numbers separated by commas and/or hyphens, making multiple intervals (pretty much like that 'page range' field found in many print dialog boxes).

For example: 1-3,9-11,17,19,21-22,25

And I need the result to be returned in another cell but with each number separated on lines, like below:

1

2

3

9

10

11

17

19

21

22

25

I can do this using excel native functions, but for only one interval (e.g.: 1-9). For anything more than that the formula doesn't work.

Is there a way to accomplish all of this in VBA?

Could some one please point me a direction?

Any help is much appreciated.

Regards

[Update]

I have using the code for some weeks, but just realized I need to avoid zeros, repeated numbers and also numbers in descending order.

e.g.

0,1,3-10,8,12,14,16,16,22,27,24-30,36,42,39

Thus, I need that a #VALUE! error message be returned if the typed numbers were not in ascending order or if zero or repeated numbers were found.

I have working on the code and already solved the aforementioned problems for only the typed intervals (x-y), but I can't figure out a solution for the discrete numbers delimited by commas.

Any help is much appreciated.

The code so far:

Function RANGEX(strInput As String) As String
Dim intCurrent  As Integer
Dim outputArray() As Variant
Dim intCount As Integer

intCount = 1

For Each i In Split(strInput, ",")
    ReDim Preserve outputArray(1 To intCount)

    If InStr(i, "-") > 0 Then
        If CInt(Split(i, "-")(0)) > 0 And CInt(Split(i, "-")(0)) < CInt(Split(i, "-")(1)) Then
            For x = CInt(Split(i, "-")(0)) To CInt(Split(i, "-")(1))
                intCurrent = x
                ReDim Preserve outputArray(1 To intCount)
                outputArray(intCount) = intCurrent
                intCount = intCount + 1
            Next x
        Else
            RANGEX = CVErr(xlErrValue)
        End If
    Else
        ReDim Preserve outputArray(1 To intCount)
        intCurrent = CInt(i)
        outputArray(intCount) = intCurrent
        intCount = intCount + 1
    End If

Next i

RANGEX = Join(outputArray, ",")

End Function

Viewing all articles
Browse latest Browse all 88066

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>