通过单行在Excel上创建唯一的SKU行

时间:2018-06-29 08:42:38

标签: excel excel-vba excel-formula excel-vba-mac vba

我在Excel中有很多行数据,每行对应一个产品。例如,我的第一行是“ Lady's Black Dress”,然后在另一个单元格中用逗号分隔大小,在一个单元格中也显示颜色。

Title           Size          Colour                 Price Before  Price After
Ladies Dress    S,M,L,XL,XXL  Blue, Black, Red       19.99          29.99
Men's Trousers  S,M,L,XL,XXL  Brown, Yellow, Orange  39.99          59.99

hj Data now

所以我需要一个VBA,该VBA为每个产品变量创建一个唯一的行(本质上是SKU),所以我的数据如下所示:

enter image description here

我之前曾问过这个问题,但仅针对2列,一个好心的人提供了该VBA,它可以工作,但我需要其他列。我不太了解如何适应此VBA,并将字母“ B”更改为“ E”,但这似乎不起作用。

Option Explicit

Sub sizeExpansion()
    Dim i As Long, szs As Variant

    With Worksheets("sheet1")
        For i = .Cells(.Rows.Count, "B").End(xlUp).Row To 2 Step -1
            szs = Split(.Cells(i, "B").Value2, ",")
            If CBool(UBound(szs)) Then
                .Cells(i, "A").Resize(UBound(szs), 1).EntireRow.Insert
                .Cells(i, "A").Resize(UBound(szs) + 1, 1) = .Cells(UBound(szs) + i, "A").Value2
                .Cells(i, "B").Resize(UBound(szs) + 1, 1) = Application.Transpose(szs)
            End If
        Next i
    End With

End Sub

1 个答案:

答案 0 :(得分:1)

尝试使用其他拆分变体和一些数学调整来进行此修改。

Option Explicit

Sub sizeAndColorExpansion()
    Dim i As Long, s As Long, c As Long
    Dim ttl As String, pb As Double, pa As Double
    Dim szs As Variant, clr As Variant

    With Worksheets("sheet1")
        For i = .Cells(.Rows.Count, "E").End(xlUp).Row To 2 Step -1
            ttl = .Cells(i, "A").Value2
            pb = .Cells(i, "D").Value2
            pa = .Cells(i, "E").Value2
            szs = Split(.Cells(i, "B").Value2, ",")
            clr = Split(.Cells(i, "C").Value2, ",")
            If CBool(UBound(szs)) Or CBool(UBound(clr)) Then
                .Cells(i, "A").Resize((UBound(szs) + 1) * (UBound(clr) + 1) - 1, 1).EntireRow.Insert
                For s = 0 To UBound(szs)
                    For c = 0 To UBound(clr)
                        .Cells(i + (s * (UBound(clr) + 1)) + c, "A").Resize(1, 5) = _
                            Array(ttl, Trim(szs(s)), Trim(clr(c)), pb, pa)
                    Next c
                Next s
            End If
        Next i
    End With

End Sub

enter image description here