根据另一个单元格中的另一个值停止该单元格中的增量值

时间:2019-05-24 07:52:47

标签: excel vba

根据my precedent post

我需要停止增量,但是我不知道...

我的代码:

Range("A2").Value = "1"
Set derlign = Range("B" & Rows.count).End(xlUp)
'MsgBox ("Dernière ligne " & derlign & " !")
Set r1 = Range("A2:A100")
Set r2 = Range("B2:B100")
For N = 2 To r2.Rows.count
    If r2.Cells(N - 1, 1) = r2.Cells(N, 1) Then
       r1.Cells(N, 1) = r1.Cells(N - 1, 1)
    Else
       r1.Cells(N, 1) = r1.Cells(N - 1, 1) + 1
    End If
Next N
End Sub`

但是那给了我:

N°  REF
1   305-77-871
2   402-88-920
2   402-88-920
3   406-55-585
3   406-55-585
3   406-55-585
4   404-11-885
4   404-11-885
4
4
4
...

您能帮我停止增加吗?

2 个答案:

答案 0 :(得分:1)

您的增量会自动在r2.Rows.count处停止,因此您需要将范围限制为拥有的数据量(而不是硬编码100)。

如果您告诉VBA,范围最大为100,则循环当然会运行到100。只需使用derlign将范围限制为B列中的数据量即可。

    Set derlign = Range("B" & Rows.count).End(xlUp)
    'MsgBox ("Dernière ligne " & derlign & " !")
    Set r1 = Range("A2:A" & derlign.Row)
    Set r2 = Range("B2:B" & derlign.Row)
    For N = 2 To r2.Rows.count
        If r2.Cells(N - 1, 1) = r2.Cells(N, 1) Then
           r1.Cells(N, 1) = r1.Cells(N - 1, 1)
        Else
           r1.Cells(N, 1) = r1.Cells(N - 1, 1) + 1
        End If
    Next N
End Sub

实际上我会将其更改为

Option Explicit

Sub WriteNumbering()
    Dim ws As Worksheet
    Set ws = ThisWorkbook.Worksheets("Sheet1")

    Dim LastRow As Long
    LastRow = ws.Range("B" & ws.Rows.Count).End(xlUp).Row

    Dim RefData As Variant 'read REF into array
    RefData = ws.Range("B2:B" & LastRow).Value

    Dim NumData As Variant 'read Num into array
    NumData = ws.Range("A2:A" & LastRow).Value

    NumData(1, 1) = 1 'start number

    Dim iRow As Long
    For iRow = LBound(RefData) + 1 To UBound(RefData) 'loop through array
        If RefData(iRow, 1) = RefData(iRow - 1, 1) Then
            NumData(iRow, 1) = NumData(iRow - 1, 1)
        Else
            NumData(iRow, 1) = NumData(iRow - 1, 1) + 1
        End If
    Next iRow

    'write the array back to the cells
    ws.Range("A2:A" & LastRow).Value = NumData
End Sub

答案 1 :(得分:0)

要尽早退出循环,您可以使用指令“退出”

If [condition] Then Exit For
相关问题