给定输入值生成所有可能的排列

osh*_*nen 3 vba microsoft-excel microsoft-excel-2016

请注意我的问题与建议的重复不同。建议的副本不会根据选项数量显示所有可能的变体,因此输入 3 可以具有输入的 1、2 和 3 变体。建议的副本始终为每个变体提供 3 个输入。

此外,我的问题还要求进行变体以显示所有可能的输入顺序。建议的副本始终在输出的最左侧位置显示 A 列,在输出中间显示 b 列,在输出左侧显示 c 列。

因此,建议重复 没有回答我的问题。


原始问题

如何创建一个公式,该公式采用任意数量的给定输入值,然后根据给定的输入值生成具有所有可能组合排列的输出值。

例如,如果输入值如下

One
Two
Run Code Online (Sandbox Code Playgroud)

生成的输出应该是这样的

One
OneTwo
Two
TwoOne
Run Code Online (Sandbox Code Playgroud)

如果给出 3 个值,它应该是什么样子:

在此处输入图片说明

有谁知道如何在Excel中做到这一点?

我希望能够输入任意数量的输入值,输入值可以是任何单词、短语、数字、字母或所有这些的组合排列。

我试过了https://www.ozgrid.com/forum/forum/help-forums/excel-vba-macros/146983-all-possible-combinations-from-single-column但它似乎不起作用.

在 A 列中,如果我输入(每行一个单词):

One
Two
Three
Run Code Online (Sandbox Code Playgroud)

在 B 列中,VBA 给了我(在单个单元格中):

one,two,three
Run Code Online (Sandbox Code Playgroud)

它没有给我所有可能的组合排列,它只是改变我垂直向下输入的内容,并水平输出结果。

har*_*ymc 5

以下 VBA 脚本为我创建了这个电子表格:

在此处输入图片说明

这是脚本:

Option Explicit

Sub PermutationsN()
Dim vElements As Variant, vresult As Variant
Dim lRow As Long, i As Long

vElements = Application.Transpose(Range("A1", Range("A1").End(xlDown)))
Columns("B:Z").Clear

For i = 1 To UBound(vElements)
    ReDim vresult(1 To i)
    Call PermutationsNPR(vElements, i, vresult, lRow, 1)
Next i
End Sub

Sub PermutationsNPR(vElements As Variant, p As Long, vresult As Variant, lRow As Long, iIndex As Integer)
Dim i As Long, unique As Variant

For i = 1 To UBound(vElements)
    vresult(iIndex) = vElements(i)
    If iIndex = p Then
        unique = UniqueArray(vresult)
        If (UBound(vresult) = UBound(unique)) Then
            lRow = lRow + 1
            Cells(lRow, 3).Value = Join(unique)
        End If
    Else
        Call PermutationsNPR(vElements, p, vresult, lRow, iIndex + 1)
    End If
Next i
End Sub


Function UniqueArray(todoarray As Variant) As Variant
  Dim arr As New Collection, a
  Dim i As Long
  On Error Resume Next
  For Each a In todoarray
     arr.Add a, a
  Next
  ReDim returnVal(1 To arr.count)
  For i = 1 To arr.count
     returnVal(i) = arr(i)
  Next
  UniqueArray = returnVal
End Function
Run Code Online (Sandbox Code Playgroud)

该宏适用于 A 列中任意数量的项目,在 Excel 范围内。