为SKU号码做While While循环

时间:2016-08-04 06:11:29

标签: excel excel-vba do-while vba

我正在尝试自动化我的SKU号码。我有3列。第一列有28,第二列有6,最后一列有58

我希望SKU有这样的趋势0{(###)col1}{(##)col2}{(##)col3}0

我的代码看起来像这样

Sub SKU()
    Dim x As Long
    x = 1
    i = 1
    j = 1
    k = 1
    Do While Cells(i, 1) <> ""
        Do While Cells(j, 2) <> ""
            Do While Cells(k, 3) <> ""
                Cells(x, 4).Value = Format(0, "0") & Format(i, "000") & _
                Format(j, "00") & Format(k, "00") & Format(0, "0")
                k = k + 1
                x = x + 1
            Loop
            j = j + 1
        Loop
        i = i + 1
    Loop
End Sub

2 个答案:

答案 0 :(得分:1)

正如我在问题评论中所提到的,删除第一个和第二个do-while循环然后替换:

Cells(x, 4).Value = Format(0, "0") & Format(i, "000") & _
           Format(j, "00") & Format(k, "00") & Format(0, "0")

使用:

Cells(k, 4) = "'" & Format(Cells(k, 1), "000") & _
           Format(Cells(k, 2), "00") & Format(Cells(k, 3), "00")

结果:0280658

如果您想添加前导零和结束零:

Cells(k, 4) = "'0" & Format(Cells(k, 1), "000") & _
           Format(Cells(k, 2), "00") & Format(Cells(k, 3), "00") & "0"

结果:002806580

答案 1 :(得分:1)

无需使用Do循环。找到最后一行,然后使用For循环。

这是你在尝试的吗?

Sub Sample()
    Dim ws As Worksheet
    Dim lRow As Long, i As Long

    '~~> Change this to the relevant sheet
    Set ws = ThisWorkbook.Sheets("Sheet2")

    With ws
        '~~> Find last row
        lRow = .Range("A" & .Rows.Count).End(xlUp).Row

        For i = 1 To lRow
            If .Cells(i, 1) <> "" And .Cells(i, 2) <> "" And .Cells(i, 3) <> "" Then

                '0{(###)col1}{(##)col2}{(##)col3}0
                .Cells(i, 4).Value = "'0" & _
                                     Format(.Cells(i, 1), "000") & _
                                     Format(.Cells(i, 2), "00") & _
                                     Format(.Cells(i, 3), "00") & _
                                     "0"
            End If
        Next i
    End With
End Sub

28,6,58的输出为002806580