【算法】Excel一组单元格为粉色,黑色,绿色,使用vba进行全排列组合之M选N
时间: 2024-01-31 07:02:14 浏览: 39
以下是使用 VBA 实现从三个颜色(粉色、黑色、绿色)中选取 M 个元素的所有组合:
```vba
Sub combination()
Dim colors As Variant
Dim n As Integer, m As Integer
Dim i As Integer, j As Integer
Dim result As String
'将颜色存储在数组中
colors = Array("粉色", "黑色", "绿色")
'输入需要选取的元素个数
n = UBound(colors) + 1
m = InputBox("请输入需要选取的元素个数:")
'如果需要选取的元素个数大于总元素个数或者小于等于0,则退出程序
If m > n Or m <= 0 Then
MsgBox "输入有误!"
Exit Sub
End If
'使用递归求解所有组合
result = ""
For i = 0 To n - m
result = result & colors(i) & ","
For j = i + 1 To n - m + 1
result = result & colors(j) & ","
Call combine(colors, j + 1, m - 2, result)
result = Left(result, Len(result) - Len(colors(j)) - 1)
Next j
result = Left(result, Len(result) - Len(colors(i)) - 1)
Next i
'输出结果
MsgBox result
End Sub
Sub combine(colors As Variant, start As Integer, count As Integer, ByRef result As String)
Dim i As Integer, j As Integer
'递归结束条件
If count = 0 Then
For i = start To UBound(colors)
result = result & colors(i) & ","
Next i
result = Left(result, Len(result) - 1) & ";"
Else
For i = start To UBound(colors) - count + 1
result = result & colors(i) & ","
Call combine(colors, i + 1, count - 1, result)
result = Left(result, Len(result) - Len(colors(i)) - 1)
Next i
End If
End Sub
```
首先将三个颜色(粉色、黑色、绿色)存储在一个数组中,然后输入需要选取的元素个数 M,使用递归实现求解所有组合。
在 `combination()` 过程中,首先判断输入是否合法,然后依次选取每一个元素为组合的第一个元素,并将剩余元素中选取 M-1 个元素的所有组合加入结果中。具体实现利用了两个循环和递归实现。
在 `combine()` 过程中,首先判断递归结束条件(即需要选取的元素个数为 0),然后依次选取每一个元素为组合的下一个元素,并将剩余元素中选取 M-2 个元素的所有组合加入结果中。递归实现需要注意的是,在递归结束后需要将已经选取的元素从结果中剔除。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)