Sub Permutations()
Dim arr(1 To 8) As Integer
Dim result() As Variant
Dim i As Integer, j As Integer, k As Integer, l As Integer, m As Integer, n As Integer, o As Integer
Dim count As Integer
count = 0
'将A1:H1单元格中的数字存储到数组中
For i = 1 To 8
arr(i) = Range("A1").Offset(0, i - 1).Value
Next i
'利用嵌套循环,对8个数字进行排列组合
For i = 1 To 3
For j = i + 1 To 4
For k = j + 1 To 5
For l = k + 1 To 6
For m = l + 1 To 7
For n = m + 1 To 8
count = count + 1
ReDim Preserve result(1 To count)
result(count) = Array(arr(i), arr(j), arr(k), arr(l), arr(m), arr(n))
Next n
Next m
Next l
Next k
Next j
Next i
'将所有不重复的排列组合结果输出到第二行
For i = 1 To count
For j = 0 To 5
Range("A2").Offset(i - 1, j).Value = result(i)(j)
Next j
Next i
End Sub
按照这个程序,如果用户在第一行输入的不一定是8个数字,有可能是7个,也有可能是10个,甚至更多,该怎么修改
以下是修改后的代码,可以适应不同数量的输入数字:
Sub Permutations()
Dim arr() As Variant
Dim result() As Variant
Dim i As Integer, j As Integer, k As Integer, l As Integer, m As Integer, n As Integer, o As Integer
Dim count As Integer
count = 0
'将A1:X1单元格中的数字存储到数组中
arr = Range("A1").Resize(1, Range("A1").End(xlToRight).Column).Value
'利用嵌套循环,对输入数字进行排列组合
For i = 1 To UBound(arr, 2) - 5
For j = i + 1 To UBound(arr, 2) - 4
For k = j + 1 To UBound(arr, 2) - 3
For l = k + 1 To UBound(arr, 2) - 2
For m = l + 1 To UBound(arr, 2) - 1
For n = m + 1 To UBound(arr, 2)
count = count + 1
ReDim Preserve result(1 To count)
result(count) = Array(arr(1, i), arr(1, j), arr(1, k), arr(1, l), arr(1, m), arr(1, n))
Next n
Next m
Next l
Next k
Next j
Next i
'将所有不重复的排列组合结果输出到第二行
For i = 1 To count
For j = 0 To 5
Range("A2").Offset(i - 1, j).Value = result(i)(j)
Next j
Next i
End Sub
在修改后的代码中,我们首先将输入数字存储到一个二维数组中,然后根据输入数字的数量确定嵌套循环的次数。具体来说,我们使用 UBound 函数来获取输入数字数组的列数,然后减去 5,因为我们每次要从中选出 6 个数字来进行排列组合。最后,我们在嵌套循环中使用 arr(1, i) 等语句来获取具体的数字值。
在加个功能,运行前先清除第二行以下下所有数据