How to Generate All Permutations in Excel
This tutorial demonstrates how to generate all permutations in Excel.
Generate All Permutations
Using the VBA macro, you can generate all possible permutations of given characters. All you need is to create a small piece of code and enter input characters. To achieve this, follow the next steps.
- In the Ribbon, go to Developer > Visual Basic. If you don’t have this tab available, find out how to add the Developer tab.
- In the VBA window, go to Insert > Module.
- In the code window on the right side, paste the following code and save.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 |
Sub GetString() Dim xStr As String Dim FRow As Long Dim xScreen As Boolean xScreen = Application.ScreenUpdating Application.ScreenUpdating = False xStr = Application.InputBox("Enter text to permute:", "Permutation", , , , , , 2) If Len(xStr) < 2 Then Exit Sub If Len(xStr) >= 8 Then MsgBox "Too many permutations!", vbInformation, "Permutation" Exit Sub Else ActiveSheet.Columns(1).Clear FRow = 1 Call GetPermutation("", xStr, FRow) End If Application.ScreenUpdating = xScreen End Sub Sub GetPermutation(Str1 As String, Str2 As String, ByRef xRow As Long) Dim i As Integer, xLen As Integer xLen = Len(Str2) If xLen < 2 Then Range("A" & xRow) = Str1 & Str2 xRow = xRow + 1 Else For i = 1 To xLen Call GetPermutation(Str1 + Mid(Str2, i, 1), Left(Str2, i - 1) + Right(Str2, xLen - i), xRow) Next End If End Sub |
- Now you have created the GetString macro, and you can run it. In the Ribbon, go to Developer > Macros.
- If it’s not already selected, select the macro, and click Run.
- In the pop-up window, enter characters for permutation (in this example, abcde), and click OK.
As a result, in Column A, you get all possible (120) permutations of entered characters.