Excel – 生成每行三组数字的笛卡尔积

我有一行数据格式如下:

设置1(仅包含一个数字)| 设置2(在唯一的单元格中包含1-6个数字)| 设置3(包含1-6独特的单元格|

例如:[1] | [1] [2] [3] | [1] [5]

输出:1 1 1,1 1 5,1 2 1,1 2 5,1 3 1,1 3 5

这是一个可以处理3个数字集的特例的VBA函数:

Function CartesianProduct(nums1 As Range, nums2 As Range, nums3 As Range) As Variant Dim n As Long 'number of products Dim i As Long, j As Long, k As Long, r As Long Dim products As Variant n = nums1.Cells.Count * nums2.Cells.Count * nums3.Cells.Count ReDim products(1 To n, 1 To 3) For i = 1 To nums1.Cells.Count For j = 1 To nums2.Cells.Count For k = 1 To nums3.Cells.Count r = r + 1 'current row products(r, 1) = nums1.Cells(i) products(r, 2) = nums2.Cells(j) products(r, 3) = nums3.Cells(k) Next k Next j Next i CartesianProduct = products End Function 

这可以从另一个VBA函数或子库中调用,或者直接作为工作表中的数组公式使用:

在这里输入图像说明

在上面的屏幕截图中,我select了范围A3:C8(需要提前确定其大小)

 =CartesianProduct(A1,B1:D1,E1:F1) 

然后通过使用Ctrl+Shift+Enter它作为数组公式Ctrl+Shift+Enter

一旦你超越了三套,事情变得有点棘手,因为你不能在一个循环的方法必要的水平硬连线,而是可能会使用recursion的方法,沿着这个答案的行: https : //stackoverflow.com /一个/4996248分之31622856

Interesting Posts