How to generate or list all possible permutations in Excel?
For example, I have three characters XYZ, now, I want to list all possible permutations based on these three characters to get six different results as this: XYZ, XZY, YXZ, YZX, ZXY and ZYX. In Excel, how could you quickly generate or list all permutations based on different number of characters?
The following VBA code may help you to list all permutations based on your specific number of letters please do as follows:
1. Hold down the ALT + F11 keys to open the Microsoft Visual Basic for Applications window.
2. Click Insert > Module, and paste the following code in the Module Window.
VBA code: List all possible permutations in excel
Sub GetString() 'Updateby Extendoffice 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:", "Kutools for Excel", , , , , , 2) If Len(xStr) < 2 Then Exit Sub If Len(xStr) >= 8 Then MsgBox "Too many permutations!", vbInformation, "Kutools for Excel" 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
3. Then press F5 key to run this code, and a prompt box is popped out to remind you enter the characters that you want to list all permutations, see screenshot:
4. After entering the characters, and then click OK button, all the possible permutations are displayed in column A of active worksheet. See screenshot:
Note: If the entered character length is equal or greater than 8 characters, this code will not work because there are too many permutations.
Best Office Productivity Tools
Supercharge Your Spreadsheets： Experience Efficiency Like Never Before with Kutools for Excel
Kutools for Excel boasts over 300 features, ensuring that what you need is just a click away...
Supports Office/Excel 2007-2021 & newer, including 365 | Available in 44 languages | Enjoy a full-featured 30-day free trial.
Office Tab Brings Tabbed interface to Office, and Make Your Work Much Easier
- Enable tabbed editing and reading in Word, Excel, PowerPoint, Publisher, Access, Visio and Project.
- Open and create multiple documents in new tabs of the same window, rather than in new windows.
- Increases your productivity by 50%, and reduces hundreds of mouse clicks for you every day!