VBScript用于按笛卡尔积拆分行

时间:2018-11-19 21:30:41

标签: excel vba excel-vba

我有一个由其他程序生成的Excel文件。 我需要以这种方式拆分和提取Excel行:

来源:

enter image description here

“拆分”操作后的Excel应该为:

enter image description here

对我来说,执行此操作的方法很明确-但我没有设法用VB编写它 逻辑应为: 我们有3列:名称,服务器,帐户->结果将为每个“名称”包含servers X accounts的笛卡尔乘积。

int Count1=1 loop for counting the number of column B (servers-separated by comma)
int Count2=1 loop for counting the number of column C (accounts-separated by comma)

1 loop i=1 from i to count1(servers)

for each server
loop: j=1 from j to count2(account)
create a new row(column A:=Name, column B:=server[i],coulmn c:=account[j]) 

move to next row 

我只需要语法方面的帮助。

1 个答案:

答案 0 :(得分:1)

尝试

Sub test()
    Dim vDB, vR(), vS(1 To 2), s
    Dim i As Long, j As Integer, n As Long
    Dim c1 As Integer, c2 As Integer

    vDB = Range("a1").CurrentRegion

    For i = 1 To UBound(vDB, 1)
        vS(1) = Split(vDB(i, 2), ",")
        vS(2) = Split(vDB(i, 3), ",")
        If InStr(vDB(i, 2), ",") Then
            c1 = 1
            c2 = 2
        Else
            c1 = 2
            c2 = 1
        End If

        For Each s In vS(c1)
            n = n + 1
            ReDim Preserve vR(1 To 3, 1 To n)
            vR(1, n) = vDB(i, 1)
            vR(c1 + 1, n) = s
            vR(c2 + 1, n) = vS(c2)(0)
        Next s
    Next i
    Sheets.Add
    Range("a1").Resize(n, 3) = WorksheetFunction.Transpose(vR)

End Sub