基于随机数生成指定长度的数字组合排列(VBA实现)
基于A列数字随机生成组合排列的VBA解决方案
我找到了问题的解决方案,现分享给大家。这段VBA代码可根据随机数结果,基于A列的数字在B列生成组合排列。
Option Explicit Public Results As Object Public MyItems As Variant Sub CallRecur() Dim i As Integer, j As Integer, rndNumb As Integer j = Cells(Rows.Count, "A").End(3).Row ReDim MyItems(j - 1) For i = 1 To j MyItems(i - 1) = Cells(i, "A") Next i Set Results = CreateObject("Scripting.Dictionary") ' 随机生成组大小,范围为2到9(Rnd返回0-1之间的随机值) rndNumb = 2 + 8 * Rnd Call Recur(UBound(MyItems), rndNumb, 0, 1, "") Range("B:B").ClearContents Range("B1").Resize(Results.Count).Value = WorksheetFunction.Transpose(Results.keys) Range("B:B").TextToColumns OtherChar:="|" End Sub ' n 为项目总数,gs 为组大小,d 为递归深度, ' curix 为当前索引,comb 为当前已生成的组合 Sub Recur(ByRef n, ByRef gs, ByVal d, ByVal curix, ByVal comb) Dim i As Long, comb2 As String For i = curix To n comb2 = comb & MyItems(i-1) & "|" If d + 1 = gs Then Results.Add comb2, 1 Else Call Recur(n, gs, d + 1, i + 1, comb2) End If Next i End Sub
效果示例
- 图1:A列输入待组合数字的初始界面
- 图2:运行代码后B列生成带分隔符的组合结果
- 图3:文本分列后拆分完成的最终组合展示
内容的提问来源于stack exchange,提问作者Ömür tokman
相关产品推荐
相关产品推荐

