在笛卡尔积中,下标超出范围误差

时间:2015-04-29 11:56:08

标签: sql excel vba excel-vba

我试图找到4列的笛卡尔积,其数据用分隔符分隔

实施例

ID                     ID2                         String           String2 
1234   33423,43222,442224,213432    Sample;repeat;example;multiple second; possible;delimiter
2345 12354; 55633; 343534;65443;121121 data;set;sample;find     answer;combination;by

我用下面的代码得到一个错误的下标超出范围。任何人都可以帮助解决它出错的地方吗?

Sub Cartesian()
    Dim MyStr1 As Variant, MyStr2 As Variant, MyStr3 As Variant, MyStr4 As Variant, _
    Str1 As Variant, Str2 As Variant, Str3 As Variant, Str4 As Variant, X As Long, _
    OrigString1 As Variant, OrigString2 As Variant, OrigString3 As Variant, _
    OrigString4 As Variant, Y As Long

    OrigString1 = Range("A2:A" & Range("A" & Rows.Count).End(xlUp).Row)
    OrigString2 = Range("B2:B" & Range("A" & Rows.Count).End(xlUp).Row)
    OrigString3 = Range("C2:C" & Range("A" & Rows.Count).End(xlUp).Row)
    OrigString4 = Range("D2:D" & Range("A" & Rows.Count).End(xlUp).Row)

    X = 2

    For Y = LBound(OrigString1) To UBound(OrigString1)

        MyStr1 = Split(OrigString1(Y), ";")
        MyStr2 = Split(OrigString2(Y), ";")
        MyStr3 = Split(OrigString3(Y), ";")
        MyStr4 = Split(OrigString4(Y), ";")

        For Each Str1 In MyStr1
            For Each Str2 In MyStr2
                For Each Str3 In MyStr3
                    For Each Str4 In MyStr4
                        Range("A" & X).Formula = Str1
                        Range("B" & X).Formula = Str2
                        Range("C" & X).Formula = Str3
                        Range("D" & X).Formula = Str4
                        X = X + 1
                    Next
                Next
            Next
        Next

    Next
End Sub

或者有没有更好的方法来处理这个使用SQL?或者使用VBA获得每行笛卡尔积的更好方法?

1 个答案:

答案 0 :(得分:0)

第一行包含逗号而不是分号,这会弄乱向量的维数