-1

我尝试根据任何单元格更改为列表创建顺序编号方法

我尝试使用 Do-While 和 Do-Until 循环更改 For-Next,但没有成功


代码

    Private Sub Worksheet_Change(ByVal Target As Range)

    Dim differnettypes As Integer
    Dim sequentialnumbering As Range
    Dim sequentialnumber As Integer

    If Not Intersect(Target, Range("B4:B30")) Is Nothing Then

        sequentialnumber = 1
        differenttypes = (Cells(Rows.Count, 3).End(xlUp).Row) - 5
        Set sequentialnumbering = Worksheets("Input").Range("B4:B30")
        For sequentialnumber = 1 To differenttypes
            sequentialnumbering.Cells(sequentialnumber, 1).Value = sequentialnumber
        Next sequentialnumber

    End If
    End Sub

C 列包含按顺序编号的内容列表,称为不同类型,以及需要剪切的其他一些信息(标题等)(因此为 -5)。

B 列包含顺序编号。在顺序编号范围 (B4:B30) 内搜索触发 sub 的更改。

当逐步调试时,我观察到代码行没有按预期的顺序执行,而是在另一个我没有经验的眼中似乎完全随机的(例如中途跳过循环,在 End sub 之后进入循环中间)。

评论中回答了问题。需要在循环内禁用事件。

4

1 回答 1

2

我编译了上面评论者的注释来修复你的代码,希望这对你有用:

Private Sub Worksheet_Change(ByVal Target As Range)

Option Explicit

Dim differenttypes As Integer
Dim sequentialnumbering As Range
Dim sequentialnumber As Integer

On Error GoTo Err_Handler
Application.EnableEvents = False

If Not Intersect(Target, Range("B4:B30")) Is Nothing Then

    differenttypes = (Cells(Rows.Count, 3).End(xlUp).Row) - 5
    Set sequentialnumbering = Worksheets("Input").Range("B4:B30")

    For sequentialnumber = 1 To differenttypes
        sequentialnumbering.Cells(sequentialnumber, 1).Value = sequentialnumber
    Next sequentialnumber

End If
Err_Handler:
    Application.EnableEvents = True
End Sub
于 2019-09-30T13:08:42.097 回答