Excel - 在每行中生成三组数字的笛卡尔积

标签 excel excel-formula cartesian-product vba

我的单行数据格式如下:

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 函数或子函数中调用,或者直接用作工作表中的数组公式:
enter image description here
在上面的屏幕截图中,我选择了范围 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/

相关文章:

ruby-on-rails - 如何在 Ruby 中将 MS Excel 日期从 float 转换为日期格式?

excel - 如何比较 COUNTIF 中的文字

javascript - 如何在 Javascript 中向 Excel 文件添加条件格式?

excel - #DIV/0! Excel Mac 2011 和 IFERROR

pandas - 获取 Pandas 数据框的多列(笛卡尔积)的组合?

python - 在 Numpy 中创建笛卡尔积时出现 MemoryError

excel - 有没有办法限制使用 VBA 删除工作表中的行?

java - 如何在 java 6 中检查 double 值是否为 Date 类型

javascript - 分区集使得笛卡尔积服从约束

excel - 复制公式的简单方法将源行扩展1?