Array Dilemma

C

Craig

I'm using Access 2002. I'm passing the values 1 through
10 (or any combination of the values) to a function. So,
the function could get passed all the numbers 1 through
10, or 1 through 4, or 1, 3, 8, 9, 10 or any combination
of the numbers 1 through 10.

I'd like the function to be able to abbreviate where there
is an incremental range of numbers - for example: 1, 2,
3, 4, 5 would be returned as "1-5". 1, 2, 3, 8 would be
returned as "1-3, 8". 1, 3, 4, 5, 6, 10 would be returned
as "1, 3-6, 10". Etc.

I'm thinking that populating an array and working with the
elements of the array would be the way to go, here. I'm
not sure how to go about it, though.

Thanks for any and all help.

C
 
F

Francesc Hervada-Sala

Hello,

I wrote this functions for you:

Public Function AbbreviateRange(ParamArray n()) As String
Dim x As Variant, a(1 To 10) As Boolean, abb As String
Dim min As Integer, max As Integer, flg As Boolean
For Each x In n
a(x) = True
Next
For x = 1 To 10
If a(x) Then
max = x
If Not flg Then min = x: flg = True
Else
If flg Then AppendRange abb, min, max
flg = False
End If
Next
If flg Then AppendRange abb, min, max
AbbreviateRange = Mid$(abb, 3)
End Function

Private Sub AppendRange(abb As String, min As Integer, max As Integer)
If min = max Then
abb = abb & ", " & min
Else
abb = abb & ", " & min & "-" & max
End If
End Sub


These are real test cases:
Debug.Print AbbreviateRange(1,3,4,5,7,8)
1, 3-5, 7-8
Debug.Print AbbreviateRange(6,7,10)
6-7, 10
Debug.Print AbbreviateRange(1,9,8)
1, 8-9
Debug.Print AbbreviateRange(10,5,2)
2, 5, 10


Bye,


Francesc
 
C

Craig

Francesc:

Thank you very much for taking the time to assist me.
This is exactly what I needed. You're very talented!

Craig
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top