如何按指定个数在Excel中获得一列数据的所有可能组合?
时间:2022-12-24 09:04:29
Q:数据放置在列A中,我要得到这些数据中任意3个数据的所有可能组合。如下图1所示,列A中存放了5个数据,要得到这5个数据中任意3个数据的所有可能组合,如列B中所示。如何实现?
图1
(注:这是无意中看到的一个问题,我觉得程序编写得很巧妙,使用了递归的方法来解决,非常简洁,特将该解答稍作整理后辑录于此与大家分享!)
A:VBA代码如下:
Sub Combinations()
Dim rng As Range
Dim n AsLong
Dim vElements As Variant
Dim lRow As Long
Dim vResult As Variant
‘要组合的数据在当前工作表的列A
Set rng =Range(“A1”, Range(“A1”).End(xlDown))
‘设置每个组合需要的数据个数
n = 3
‘在数组中存储要组合的数据
vElements =Application.Index(Application.Transpose(rng), 1, 0)
‘重定义进行组合的数组大小
ReDim vResult(1 To n)
Call CombinationsREC(vElements, CInt(n), vResult, lRow, 1, 1)
End Sub
Sub CombinationsREC(vElements As Variant, _
p As Integer,_
vResult AsVariant, _
lRow As Long,_
iElement AsInteger, _
iIndex AsInteger)
Dim i AsInteger
For i =iElement To UBound(vElements)
vResult(iIndex)= vElements(i)
IfiIndex = p Then
lRow = lRow + 1
Range(“B” & lRow) = Join(vResult, “, “)
‘每组组合放置在多列中
Range(“C” &lRow).Resize(, p) = vResult
Else
‘递归调用
Call CombinationsREC(vElements, p, vResult, lRow, i + 1, iIndex + 1)
End If
Next i
End Sub
代码的关键在于递归调用的实现,有兴趣的朋友可以使用F8键逐语句运行代码观察代码效果,来理解实现过程。
代码的图片版如下:
如果将代码中注释掉的代码恢复,也就是将组合结果放置在多列中,运行后的结果如下图2所示。
![](/images/zang.png)
![](/images/jiucuo.png)
猜你喜欢
excel迷你图,表达数据简洁醒目
![](https://img.aspxhome.com/file/2023/3/a142233_0s.jpg)
最新版Office 2016 带来黑色主题 如何使用
![](https://img.aspxhome.com/file/2023/4/16384_0s.jpg)
word2013怎么设置图片排版
Excel表格技巧_Excel如何做函数图像
![](https://img.aspxhome.com/file/2023/8/a140788_0s.jpg)
Word如何使用通配查找替换
![](https://img.aspxhome.com/file/2023/3/33633_0s.png)
Word文档左边的竖线怎么去掉?
![](https://img.aspxhome.com/file/2023/2/30582_0s.jpg)
win10中怎么删除微软拼音输入法?win10删除微软拼音输入法的方法教程?
![](https://img.aspxhome.com/file/2023/4/47254_0s.jpg)
如何在word中输入带钩的方框
word页面怎么设置为A3打印格式
常用25条Excel技巧
Win10检测不到其它显示器怎么办?Win10检测不到其它显示器的解决办法
![](https://img.aspxhome.com/file/2023/4/52124_0s.jpg)
Excel2019输入数字后直接变成日期格式怎么设置?
![](https://img.aspxhome.com/file/2023/6/40026_0s.jpg)
excel中人名币符号怎么输入
![](https://img.aspxhome.com/file/2023/6/36716_0s.jpg)
word带圈字符怎么打
![](https://img.aspxhome.com/file/2023/2/34622_0s.gif)
Excel2010如何设置分数类型数字格式
![](https://img.aspxhome.com/file/2023/9/37169_0s.png)
Word文档批量删除英文字母的操作方法分享
![](https://img.aspxhome.com/file/2023/8/30978_0s.png)
windows7系统解除管理员权限禁用教程
![](https://img.aspxhome.com/file/2023/7/53347_0s.jpg)
word 表格中怎样快速插入序号?
![](https://img.aspxhome.com/file/2023/5/32425_0s.jpg)