我的单行数据格式如下:
Set 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
最佳答案
这是一个 VBA 函数,它可以处理 3 个数字集的特殊情况:
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 函数或子函数中调用,或者直接用作工作表中的数组公式:在上面的屏幕截图中,我选择了范围 A3:C8(需要提前确定其大小)输入公式
=CartesianProduct(A1,B1:D1,E1:F1)
然后通过输入 Ctrl+Shift+Enter
将其作为数组公式接受.一旦超过三组,事情就会变得有点棘手,因为你不能硬连线循环方法的必要级别,而是可能使用递归方法,类似于这个答案:https://stackoverflow.com/a/31622856/4996248
关于Excel - 在每行中生成三组数字的笛卡尔积,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42749944/