Перейти к основному содержанию

Как сгенерировать или перечислить все возможные перестановки в Excel?

Например, у меня есть три символа XYZ, теперь я хочу перечислить все возможные перестановки на основе этих трех символов, чтобы получить шесть разных результатов, например: XYZ, XZY, YXZ, YZX, ZXY и ZYX. Как в Excel быстро сгенерировать или составить список всех перестановок на основе разного количества символов?

Сгенерировать или перечислить все возможные перестановки на основе символов с кодом VBA


стрелка синий правый пузырь Сгенерировать или перечислить все возможные перестановки на основе символов с кодом VBA

Следующий код VBA может помочь вам перечислить все перестановки на основе вашего конкретного количества букв, пожалуйста, сделайте следующее:

1. Удерживайте ALT + F11 , чтобы открыть Microsoft Visual Basic для приложений окно.

2. Нажмите Вставить > Модулии вставьте следующий код в Модули Окно.

Код VBA: список всех возможных перестановок в 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, Затем нажмите F5 нажмите клавишу для запуска этого кода, и появится окно подсказки, напоминающее вам ввести символы, которые вы хотите перечислить, все перестановки, см. снимок экрана:

перестановки списка документов 1

4. После ввода символов, а затем нажмите OK все возможные перестановки отображаются в столбце A активного рабочего листа. Смотрите скриншот:

перестановки списка документов 2

Внимание: Если длина введенного символа равна или превышает 8 символов, этот код не будет работать, потому что существует слишком много перестановок.

перестановки списка документов 3


Перечислите или сгенерируйте все возможные комбинации из нескольких столбцов

Если вам нужно сгенерировать все возможные комбинации на основе данных из нескольких столбцов, возможно, нет хорошего способа справиться с задачей. Но, Kutools for Excel's Список всех комбинаций Утилита поможет вам быстро и легко перечислить все возможные комбинации. Нажмите, чтобы загрузить Kutools for Excel!

документ перечислить все комбинации

Kutools for Excel: с более чем 300 удобными надстройками Excel, которые можно попробовать бесплатно без ограничений в течение 30 дней. Загрузите и бесплатную пробную версию прямо сейчас!

Лучшие инструменты для офисной работы

🤖 Kutools AI Помощник: Революционный анализ данных на основе: Интеллектуальное исполнение   |  Генерировать код  |  Создание пользовательских формул  |  Анализ данных и создание диаграмм  |  Вызов функций Kutools...
Популярные опции: Найдите, выделите или определите дубликаты   |  Удалить пустые строки   |  Объедините столбцы или ячейки без потери данных   |   Раунд без формулы ...
Супер поиск: Множественный критерий VLookup    VLookup с несколькими значениями  |   VLookup по нескольким листам   |   Нечеткий поиск ....
Расширенный раскрывающийся список: Быстрое создание раскрывающегося списка   |  Зависимый раскрывающийся список   |  Выпадающий список с множественным выбором ....
Менеджер столбцов: Добавить определенное количество столбцов  |  Переместить столбцы  |  Переключить статус видимости скрытых столбцов  |  Сравнить диапазоны и столбцы ...
Рекомендуемые функции: Сетка Фокус   |  Просмотр дизайна   |   Большой Формулный Бар    Менеджер книг и листов   |  Библиотека ресурсов (Авто текст)   |  Выбор даты   |  Комбинировать листы   |  Шифровать/дешифровать ячейки    Отправлять электронные письма по списку   |  Суперфильтр   |   Специальный фильтр (фильтровать жирным шрифтом/курсивом/зачеркиванием...) ...
15 лучших наборов инструментов12 Текст Инструменты (Добавить текст, Удалить символы, ...)   |   50+ График Тип (Диаграмма Ганта, ...)   |   40+ Практических Формулы (Рассчитать возраст по дню рождения, ...)   |   19 Вносимые Инструменты (Вставить QR-код, Вставить изображение из пути, ...)   |   12 Конверсия Инструменты (Числа в слова, Конверсия валюты, ...)   |   7 Слияние и разделение Инструменты (Расширенные ряды комбинирования, Разделить клетки, ...)   |   ... и более

Улучшите свои навыки работы с Excel с помощью Kutools for Excel и почувствуйте эффективность, как никогда раньше. Kutools for Excel предлагает более 300 расширенных функций для повышения производительности и экономии времени.  Нажмите здесь, чтобы получить функцию, которая вам нужна больше всего...

Описание


Вкладка Office: интерфейс с вкладками в Office и упрощение работы

  • Включение редактирования и чтения с вкладками в Word, Excel, PowerPoint, Издатель, доступ, Visio и проект.
  • Открывайте и создавайте несколько документов на новых вкладках одного окна, а не в новых окнах.
  • Повышает вашу продуктивность на 50% и сокращает количество щелчков мышью на сотни каждый день!
Comments (13)
No ratings yet. Be the first to rate!
This comment was minimized by the moderator on the site
Olá !

Como faço para gerar pelo menos 10 permutações ?
This comment was minimized by the moderator on the site
Hello, Mateus,
To solve your problem, please apply the below code:(Note: if there are more than 8 characters, the code will execute slowly.)
Sub GetString()
'Updateby Extendoffice
    Dim xStr As String
    Dim FRow As Long
    Dim FC As Integer
    Dim xScreen As Boolean
    Dim xNumber As Long
    xNumber = 10 ' This is the max length of the characters you can change it to 11, 12, 13...as you need
    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) > xNumber Then
        MsgBox "Too many permutations!", vbInformation, "Kutools for Excel"
        Exit Sub
    Else
        ActiveSheet.Columns(1).Clear
        FRow = 1
        FC = 1
        Call GetPermutation("", xStr, FRow, FC)
    End If
    Application.ScreenUpdating = xScreen
End Sub
Sub GetPermutation(Str1 As String, Str2 As String, ByRef xRow As Long, ByRef xc As Integer)
    Dim i As Integer, xLen As Integer
    xLen = Len(Str2)
    If xLen < 2 Then
        If xRow > 1000000 Then
            xc = xc + 1
            xRow = 1
        End If
       ActiveSheet.Cells(xRow, xc) = 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, xc)
        Next
    End If
End Sub


Please have a try, hope it can help you!
This comment was minimized by the moderator on the site
Hi there, if the input string contains duplicate chars, then the sub produces duplicate permutations.
This does not happen if you make the following modification the the loop:

' ==========================
For i = 1 To xLen
If Instr( Left(Str2, i - 1), Mid(Str2, i, 1) ) = 0 then
Call GetPermutation(Str1 + Mid(Str2, i, 1), Left(Str2, i - 1) + Right(Str2, xLen - i), xRow)
End if
Next
' ==========================

Creating temporary local variables for Mid(Str2, i, 1) and for Left(Str2, i - 1), and avoiding the test for i=1 makes it go faster:


' ==========================
Sub GetPermutation(Str1 As String, Str2 As String, ByRef xRow As Long)
Dim i As Integer, xLen As Integer, Str2left as String, c as String
xLen = Len(Str2)
If xLen < 2 Then
Range("A" & xRow) = Str1 & Str2
xRow = xRow + 1
Else
Call GetPermutation(Str1 + Mid(Str2, 1, 1), Right(Str2, xLen - 1), xRow)
For i = 2 To xLen
c = Mid(Str2, i, 1)
Str2left = Left(Str2, i - 1)
If Instr( Str2left, c ) = 0 then
Call GetPermutation(Str1 + c, Str2left + Right(Str2, xLen - i), xRow)
End If
Next
End If
End Sub
' ==========================

Cheers,
DVdm
This comment was minimized by the moderator on the site
who can send me a list of 10 diferent items permutatted by 2 outcomes. this code doe

snt work on this
This comment was minimized by the moderator on the site
peki bunu listeleyecek bir program uygulama yok mu?basit sıradan bir hesaplamadan daha fazlasına ihtiyacı olan ne yapacak?
This comment was minimized by the moderator on the site
this code will not work because there are two many permutations


should be:

this code will not work because there are too many permutations


HTH
This comment was minimized by the moderator on the site
Hello, MC,
Thank you for your warm reminder, it is my mistake. I have corrected it.
Thanks a lot!
This comment was minimized by the moderator on the site
Hello everyone. I need help on this. I have two alphabets to be permutated in 20 rows. But am not getting it right. Anyone who could help me out should send the permutation to my email. .


1.a b b a
2.a a b b
3.a a b b
4.a a b b
5.a a b b
6.a a b b
7.a a b b
8.a a b b
9.a a b b
10.a a b b
11.a a b b
12.a a b b
13.a a b b
14.a a b b
15.a a b b
16.a a b b
17.a a b b
18.a a b b
19.a a b b
20.a a b b
This comment was minimized by the moderator on the site
How many sequences of 3things can be formed from 7 different things replacement and order is important?
This comment was minimized by the moderator on the site
3 to the power of 7: 2187
This comment was minimized by the moderator on the site
@Supraja...

in the first sub clear all cells... not just the first row
--Cells.Clear

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
'move to the next column when you get to 100
Cells(((xRow - 1) Mod 100) + 1, 1 + Int(xRow / 100)) = 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
This comment was minimized by the moderator on the site
Hello,

Im trying to get a permutation for 82 characters, the code provided works, but, since the columns are only 1048576, I want to move the next output in B,C,D..... Can any of you help me on this regard
This comment was minimized by the moderator on the site
Hello, Im doing a small project using permutation and combination rules. I need your support on this please. Scenario: I have 13 digit alpha numeric data (00SHGO8BJIDG0) I want a coding to interchange S to 5, I to 1 and O to 0 and vise versa. The project is that if I have the correct 13 digit data I will receive a 3 digit pass code. (eg) 00SHG08BJ1DG0 - 500 is the pass code but because of wrong typo that is instead of 1 it was I and 0 it was O there is a wrong info. can you please help me.
There are no comments posted here yet
Please leave your comments in English
Posting as Guest
×
Rate this post:
0   Characters
Suggested Locations