如何对范围内的一个单元格值进行编号,然后在单元格值更改时重新开始编号

How can you number one cell value in a range and then start the numbering over when the value of the cell changes

我有一个范围,范围内可以有多个值,但值可以重复。我试图编写一个可以执行此操作的宏,但遇到了障碍。我可以对整个范围内的单元格进行编号,从 1 到范围末尾的任何计数。这是我到目前为止的代码以及结果的列表。第二个列表是我最终的结果。

Sub Count_Items_Then_Repeat_On_Data_Change()

Dim rng As Range

Dim cell As Range

Dim count As Long

count = 1

Set rng = Application.Selection

For Each cell In rng

cell.Offset(0, 0).Value = cell.Value & "-" & count

count = count + 1


Next cell


End Sub
Wrong Output Correct Output
Column A Column A
1 1.01-1 1.01-1
2 1.01-2 1.01-2
3 1.01-3 1.01-3
4 1.01-4 1.01-4
5 1.02-5 1.02-1
6 1.02-6 1.02-2
7 1.02-7 1.02-3
8 1.02-8 1.02-4

根据数据以及您似乎想做什么,我不确定我是否理解您的问题。

您似乎希望在单元格的原始值发生变化时重置计数。

如果整个选择是有序的,您可以在更改前简单地测试下一个单元格,看看计数是否应该像这样重置:

Sub Count_Items_Then_Repeat_On_Data_Change()
    Dim rng As Range
    Dim cell As Range
    Dim count As Long
    count = 1
    Set rng = Application.Selection
    For Each cell In rng
        'If the next cell has a different value, reset count after we change this one
        If cell.Value <> cell.Offset(1, 0).Value Then
            cell.Value = cell.Value & "-" & count
            count = 1 'Reset count to 1
        Else
            cell.Value = cell.Value & "-" & count
            count = count + 1
        End If
    Next cell
End Sub

我也继续更改 cell.Offset(0,0).Value - 你不需要 .Offset(0,0) - 它什么都不做;你可以只使用 cell.Value.

结果: