Need code to pair off numbers

D

davidm

I have been grappling with an idea of setting off pairs (even clusters)
of numbers *using code *as in (1,2,3); (4,5,6); (7,8,9) ... (58,59,60)
for a data range 1-60 in this case. This is easily accomplished on
worksheet but I need results that can be stored in, and retrieved from
an array. In the generalized case, I would want the code to trussle up
n elements, where n can be any number not more than the count of
elements in the data range population set.

Thus, in the current instance, the code should be adaptable to draw out
(1,2);(3,4);(5,6)... where n=2 as well as (1,2,3,4,5), (6,7,8,9,10) ...
where n=5. The attempted code below further illustrates what I am
groping for.

Sub Cluster3Elements()
Dim arr()
n = 0
For i = 1 To 60 Step 3
ReDim Preserve arr(n)
arr(i) = i & "," & i + 1 & "," & i + 2 ===> Subscript Out of range
error
n = n + 1
Next
'test
For j = LBound(arr) To UBound(arr)
Debug.Print arr(j)
Next
End Sub

TIA.

Davidm
 
T

Tim Williams

Why bother with filliang an array? Can't you just generate the clusters on
demand?

Anyway - a simplistic approach

*****************************
Sub Tester()
Dim a
a = ClusterElements(1, 60, 3)
Debug.Print Join(a, vbCrLf)
End Sub

Function ClusterElements(lStart, lEnd, iGroup) As Variant
Dim arr(), n, i, j
n = 1
For i = lStart To lEnd Step iGroup
ReDim Preserve arr(n)
For j = 0 To iGroup - 1
arr(n) = arr(n) & _
IIf(Len(arr(n)) = 0, "", ",") & i + j
Next j
n = n + 1
Next i

ClusterElements = arr
End Function
**********************************

Tim
 

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