首页 > 解决方案 > 在一个 Excel 表中创建属性值的笛卡尔积

问题描述

如何在(Excel)VBA中创建多个属性的属性值的笛卡尔积,存储在同一个表中?

代码应处理动态数量的属性(第一列)和每个属性的属性值(第二列)。

输入示例:

结果:

Power Query for Excel 中的解决方案对我来说也可以。

对于固定数量的属性,我可以将属性值存储在每个属性的数组中,然后使用嵌套的 for 循环。但我正在寻找具有动态数量属性的解决方案。

这是我为固定数量的属性创建的代码。注意:从 Excel 表中填充数组不是问题,所以我省略了这一点,直到我找到了 Cartesion 产品的解决方案。

Sub GenerateItems()

Dim strAttributeValues1 As String
Dim strAttributeValues2 As String
Dim strAttributeValues3 As String

Dim arrAttributeValues1() As String
Dim arrAttributeValues2() As String
Dim arrAttributeValues3() As String

Dim strItemName As String

strAttributeValues1 = "A1,A2,A3"
arrAttributeValues1 = Split(strAttributeValues1, ",")

strAttributeValues2 = "B1,B2"
arrAttributeValues2 = Split(strAttributeValues2, ",")

strAttributeValues3 = "C1"
arrAttributeValues3 = Split(strAttributeValues3, ",")

Dim a, b, c As Integer

For a = 0 To UBound(arrAttributeValues1)
    For b = 0 To UBound(arrAttributeValues2)
        For c = 0 To UBound(arrAttributeValues3)
            strItemName = arrAttributeValues1(a) & " " & arrAttributeValues2(b) & " " & arrAttributeValues3(c)
            Debug.Print strItemName
        Next c
    Next b
Next a

End Sub

标签: excelvba

解决方案


推荐阅读