DC娱乐网

如何在 Excel 中列出 6 个字符中所有 4 个字符的组合?

解答网友问题:如何列举出 6 个字符中所有 4 个字符的排列组合?不考虑排列顺序。案例:列出字母 A、B、C、D、E、F

解答网友问题:如何列举出 6 个字符中所有 4 个字符的排列组合?不考虑排列顺序。

案例:

列出字母 A、B、C、D、E、F 中任意 4 个字母的排列组合。组合中的字母相同、排列顺序不同视为同一个。

效果如下图所示。

解决方案:

1. 按 Alt+F11 打开 VBE --> 输入以下代码:

Public Sub GenerateCombinations()

Dim sourceStr As String

Dim result As Collection

Dim outputRow As Integer

' 初始化参数

sourceStr = "ABCDEF" ' 可替换为任意6个字符

Set result = New Collection

outputRow = 2

' 准备输出工作表

With ActiveSheet

.Cells.Clear

.Range("A1").Value = "组合结果 (源字符: " & sourceStr & ")"

.Range("B1").Value = "总数"

End With

' 调用核心组合生成算法

Call GetCombinations(sourceStr, 4, "", 1, result) '任意4个字符的组合;如果改成5就可以得到任意5个字符的组合

' 输出结果

For Each Item In result

ActiveSheet.Cells(outputRow, 1).Value = Item

outputRow = outputRow + 1

Next

' 显示统计信息

With ActiveSheet

.Range("B2").Value = result.Count

.Columns("A:B").AutoFit

End With

MsgBox "成功生成 " & result.Count & " 种组合", vbInformation, "完成"

End Sub

Private Sub GetCombinations(source As String, remain As Integer, _

current As String, startPos As Integer, _

ByRef result As Collection)

' 终止条件:组合长度达标

If remain = 0 Then

result.Add current

Exit Sub

End If

' 递归生成组合

Dim i As Integer

For i = startPos To Len(source) - remain + 1

GetCombinations source, remain - 1, _

current & Mid(source, i, 1), _

i + 1, result

Next

End Sub

2. 点击“运行”按钮运行代码。

以下就是运行结果。

3. 关闭对话框。