Please Note: This article is written for users of the following Microsoft Excel versions: 2007, 2010, and 2013. If you are using an earlier version (Excel 2003 or earlier), this tip may not work for you. For a version of this tip written specifically for earlier versions of Excel, click here: Listing Combinations.

Listing Combinations

by Allen Wyatt
(last updated October 12, 2013)

9

Ron knows he can use the COMBIN function to determine the number of combinations that can be made from a number of digits. He's wondering, however, if there is a way to list out all the combinations themselves.

There is no built-in way to list combinations in Excel. You can, however, create a macro to do the listing for you. If you want to find the unique combinations in a set of sequential numbers starting at 1, then the following set of macros will do the trick. All you need to do is run the function TestCNR and you will end up with a "matrix" of cells that represent the number of 4-digit combinations in the sequential set of values ranging from 1 to 10.

Sub TestCNR()
    Cnr 10, 4
End Sub
Sub Cnr(n, r)
    i = 1
    For j = 1 To r
        Cells(i, j).Value = j
    Next

    Do Until Finished(n, r, i)
        j = FindFirstSmall(n, r, i)
        For k = 1 To j – 1
            Cells(i + 1, k).Value = Cells(i, k).Value
        Next
        Cells(i + 1, j).Value = Cells(i, j).Value + 1
        For k = j + 1 To r
            Cells(i + 1, k).Value = Cells(i + 1, k - 1).Value + 1
        Next
        i = i + 1
    Loop
End Sub
Function Finished(n, r, i)
    Temp = True

    For j = r To 1 Step -1
        If Cells(i, j).Value <> j + (n - r) Then
            Temp = False
        End If
    Next
    Finished = Temp
End Function
 
Function FindFirstSmall(n, r, i)
    j = r
    Do Until Cells(i, j).Value <> j + (n - r)
        j = j - 1
    Loop
    FindFirstSmall = j
End Function

The macro overwrites whatever is in your worksheet, so make sure you run the test with a blank worksheet displayed. If you want to change the size of the set or the number of elements in the subset, just change the values passed in the TestCNR routine.

If you want to pull unique combinations from a string of characters (for instance, the letters of the alphabet), then you need to use a different set of macros. The following will work fine; it assumes that the characters you want to use as your "universe" is in cell A1 and the number you want in each unique combination is in cell A2.

Sub FindSets()
    Dim iA() As Integer
    Dim sUniv As String
    Dim iWanted As Integer
    Dim j As Integer
    Dim k As Integer

    sUniv = Cells(1, 1).Value
    iWanted = Cells(2, 1).Value

    ReDim iA(iWanted)
    For j = 1 To iWanted
        iA(j) = j
    Next j

    iRow = PutRow(iA, sUniv, 1)

    Do Until DoneYet(iA, Len(sUniv))
        j = WorkHere(iA, Len(sUniv))
        iA(j) = iA(j) + 1
        For k = j + 1 To iWanted
            iA(k) = iA(k - 1) + 1
        Next k
        iRow = PutRow(iA, sUniv, iRow)
    Loop
End Sub
Function DoneYet(iB, n) As Boolean
    iMax = UBound(iB)
    Temp = True
    For j = iMax To 1 Step -1
        If iB(j) <> j + (n - iMax) Then
            Temp = False
        End If
    Next
    DoneYet = Temp
End Function
Function WorkHere(iB, n) As Integer
    iMax = UBound(iB)
    j = iMax
    Do Until iB(j) <> j + (n - iMax)
        j = j - 1
    Loop
    WorkHere = j
End Function
Function PutRow(iB, sUniv, i)
    iMax = UBound(iB)
    sTemp = ""
    For j = 1 To iMax
        sTemp = sTemp & Mid(sUniv, iB(j), 1)
    Next j
    Cells(i, 2).Value = sTemp
    PutRow = i + 1
End Function

Run the FindSets macro and the different combinations desired end up in column 2. Be careful when running the macro, however. The number of combinations can get very large very quickly.

ExcelTips is your source for cost-effective Microsoft Excel training. This tip (11891) applies to Microsoft Excel 2007, 2010, and 2013. You can find a version of this tip for the older menu interface of Excel here: Listing Combinations.

Author Bio

Allen Wyatt

With more than 50 non-fiction books and numerous magazine articles to his credit, Allen Wyatt is an internationally recognized author. He  is president of Sharon Parq Associates, a computer and publishing services company. ...

MORE FROM ALLEN

Deleting Paragraph Borders

Got a document that has a border around some paragraphs? Here's how you can get rid of the border in the fastest way ...

Discover More

Converting to Automatic Endnotes

When you add endnotes to a document, they are automatically maintained and renumbered by Word, as necessary. If you get a ...

Discover More

Pop-Up Comments for Graphics

Excel allows you to add comments to individual cells in a worksheet, but what if you want to add comments to graphics? Excel ...

Discover More

Program Successfully in Excel! John Walkenbach's name is synonymous with excellence in deciphering complex technical topics. With this comprehensive guide, "Mr. Spreadsheet" shows how to maximize your Excel experience using professional spreadsheet application development tips from his own personal bookshelf. Check out Excel 2013 Power Programming with VBA today!

More ExcelTips (ribbon)

Last Non-Zero Value in a Row

If you have a lot of values in a single row, you might want to pull the last non-zero value from that row. There are a ...

Discover More

Tracing Errors

Sometimes it can be confusing to figure out the source of an error that is displayed in your worksheet. Excel provides a ...

Discover More

Dealing with Circular References

Circular references occur when a formula includes a reference to the cell in which the formula appears. Here's how you can ...

Discover More
Subscribe

FREE SERVICE: Get tips like this every week in ExcelTips, a free productivity newsletter. Enter your address and click "Subscribe."

View most recent newsletter.

Comments

If you would like to add an image to your comment (not an avatar, but an image to help in making the point of your comment), include the characters [{fig}] in your comment text. You’ll be prompted to upload your image when you submit the comment. Maximum image size is 8Mpixels. Images larger than 600px wide or 1000px tall will be reduced. Up to three images may be included in a comment. All images are subject to review. Commenting privileges may be curtailed if inappropriate images are posted.

What is 0 + 7?

2017-01-18 10:18:13

greg

Actually, the method is quite brilliant. I went through the code step by step and its great


2016-02-10 07:55:17

allen@sharonparq.com

Fred: You can sign up using the form at the right side of this page or any page on this site.

-Allen


2016-02-09 22:25:47

Fred Mirande

Hi Allen,
I have been a long time subscriber to daily tips Excel 2007.
Laptop died some months back after retirement. Did not think I would get another, but, I did and now realise that I miss your tips. Please can I subscribe with my new email address. I was lmirande@bigpond but is not now. Thanks, Kind Regards Fred Mirande9


2015-01-04 00:09:49

Steve

I am interested in a prog like the TestCNR, but I too am running into problems with it. IT loops endlessly, syntax errors etc There appear to be a lot of opportunity for improving and assume by now is ironed out. Can you repost or sent the improved version. Much appreciated.


2014-04-25 21:44:57

Zefs

Hi Micky,
I have been mucking around for a while.
Could you add the changes in the Macro below as I have been unsuccessful. I would like the Combination Generator to continue to sheet 2 & 3 & 4... if needed etc, etc if it exceeds the sheet limit of 1048575. Also to numer the combinations starting in column A and continuing to the following sheets.
Regards, Zefs.

Sub TestCNR()
Cnr 10, 4
End Sub
Sub Cnr(n, r)
i = 1
For j = 1 To r
Cells(i, j).Value = j
Next

Do Until Finished(n, r, i)
j = FindFirstSmall(n, r, i)
For k = 1 To j – 1
Cells(i + 1, k).Value = Cells(i, k).Value
Next
Cells(i + 1, j).Value = Cells(i, j).Value + 1
For k = j + 1 To r
Cells(i + 1, k).Value = Cells(i + 1, k - 1).Value + 1
Next
i = i + 1
Loop
End Sub
Function Finished(n, r, i)
Temp = True

For j = r To 1 Step -1
If Cells(i, j).Value <> j + (n - r) Then
Temp = False
End If
Next
Finished = Temp
End Function

Function FindFirstSmall(n, r, i)
j = r
Do Until Cells(i, j).Value <> j + (n - r)
j = j - 1
Loop
FindFirstSmall = j
End Function


2014-04-08 04:28:12

Zefs

Micky,

Thanks so much for the reply.
I see you commented on the second Macro. For some reason I couldn't get that working. I am using the first Macro and it is quite different. Do you mind having a look at what the solution would be for that Macro. Sorry, but a newbie.
Regards,
Zefs,
Tasmania.


2014-04-07 11:17:33

Michael (Micky) Avidan

@Zefs,
You need to make some minor changes.
In the the main macro put a variable LC, give it the value of 2 (LC = 2) and send fourth variable, to the "PutRow" Function.
This variable will serve for the column number.
So, insted of: Cells(i, 2).Value = sTemp
Use: Cells(i, LC).Value = sTemp

All you need, now, is to check/find out when does the row counter (i) reaches: 1048575 and if so, increase the LC by 1 (LC = LC +1) in order to put the next value in row 1 of the next(!) column.
All the above are general instructions given from a short look at the proposed macros (I didn't check this out).
Michael (Micky) Avidan
“Microsoft® Answers" - Wiki author & Forums Moderator
“Microsoft®” MVP – Excel (2009-2014)
ISRAEL


2014-04-06 10:59:16

Zefs

Hi, thanks for that. I was scouring the web all day looking for this macro.
Problem I have been having for a while is my exc2007 only has a limit up to approx 1.04million rows. When the combinations reach this target, the macro stops producing combinations. Is there any way to extend the rows in the page, be it via an after market add in or hacking excel somehow? If Not, can the Macro continue producing the combinations to a new page tab. If so, what is important to me is that the row number of the combination continues to the next page rather than starting from 1 again. If the row number cannot continue, can the macro be enabled to have the combination number in row A and continue to the next pages?
Regards, Zefs.


2013-10-15 13:31:18

Bryan

Yikes, these macros are messy. I'm having a hard time understanding them (ok, I'll admit it: I just plain don't understand them). Here are some tips that would help clarify, clean, and speed up the macros:

1. All variables should be dimensioned. If you have the "Require Variable Declaration" option checked (aka Option Explicit), as you should, the macros won't compile. It also makes it easier to tell what the variables are supposed to be.
2. Function inputs and outputs should have a declared type, not an implicit Variant type.
3. The i/j/k variables are fine (by convention, counter variables are often single letters starting with i), but the rest of the variables could be more clearly named.
4. Similarly, some of the functions are cryptically named. "CNR" means... COMBIN n r? Why not ListCombinations? "Finished" and "DoneYet" are more or less clear enough, "FindFirstSmall" and "PutRow" are mediocre, and "WorkHere" is just downright useless.
5. Since Finished and DoneYet don't need to continue looping once Temp = False, you should add an Exit For condition so you aren't needlessly looping.
6. With all the loops and subroutines, a couple comments would go a long way to explaining what is going on. Something as simple as "' This routine determines if we have reached the last combination" is all that is needed for "Finished", for example. Another comment on how the "last combination" is determined wouldn't hurt either.
7. Hard-coding an output range without any sort of check is a Very Bad Idea. At a minimum you should (a) prompt the user or somehow let the user choose an output range (by using the Selection object, for example; one of the few good uses of this object); (b) check how many rows will be occupied to determine if you will have enough room (choosing 8 letters from the alphabet gives >1.5m combinations; too great to fit within the sheet) and that there's nothing currently occupying the space; and (c) clear the space needed and possibly the surrounding area (cnr 10, 4 followed by cnr 5, 4 will give the appearance of an incorrect result).
8. Application.ScreenUpdating = False will drastically speed up large number of combinations; using a variant array and putting it all back to the sheet at once will increase the speed even more
9. I'm sure there are more, but as I mentioned I just can't follow the code well enough to suggest any substantial changes.


This Site

Got a version of Excel that uses the ribbon interface (Excel 2007 or later)? This site is for you! If you use an earlier version of Excel, visit our ExcelTips site focusing on the menu interface.

Newest Tips
Subscribe

FREE SERVICE: Get tips like this every week in ExcelTips, a free productivity newsletter. Enter your address and click "Subscribe."

(Your e-mail address is not shared with anyone, ever.)

View the most recent newsletter.