How can excel generate every unique pair from a set of numbers?

M

mistermat

If I have a set of unique numbers, for example:

1
2
3
4

how can i use excel to generate every unique pair automatically in two
separate columns, for example:

1 2
1 3
1 4
2 1
2 3
2 4
3 1
3 2
3 4
4 1
4 2
4 3
 
M

Mike H

Hi,

This assumes you numbers are in column A and it will output to columns B & C

Right click your sheet tab, view code and past this in and run it

Sub stantial()
Range("B1:C" & Cells(Rows.Count, "B").End(xlUp).Row).ClearContents
myrow = 1
lastrow = Cells(Rows.Count, "A").End(xlUp).Row
For x = 1 To lastrow
For y = x + 1 To lastrow
Cells(myrow, 2).Value = Cells(x, 1).Value
Cells(myrow, 3).Value = Cells(y, 1).Value
myrow = myrow + 1
Cells(myrow, 2).Value = Cells(y, 1).Value
Cells(myrow, 3).Value = Cells(x, 1).Value
myrow = myrow + 1
Next
Next
Range("B1:C" & Cells(Rows.Count, "B").End(xlUp).Row).Select
Selection.Sort Key1:=Range("B1"), Order1:=xlAscending
End Sub

Mike
 
Joined
Aug 27, 2008
Messages
44
Reaction score
0
If your numbers are in A1 and downward, putting this formula in B1 and dragging down will work.
=INDEX(A:A,MOD(INT((ROW()-1)/COUNT(A:A)),COUNT(A:A))+1,1) &","& INDEX(A:A,MOD(ROW()-1,COUNTA(A:A))+1,1)
 

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