插入行时让数字自动向上移动

时间:2017-03-09 20:05:03

标签: excel vba excel-vba

目前正在使用Excel工作表对项目进行排名,如果我们插入新行并输入现有的数字排名,我们希望它自动增加数字。如果我们输入一行并输入9作为其排名,我们希望预先存在的9移动到10而旧的10移动到11等等。我有点解决了,但是我的代码自动将第一行编号为1等等。这是我到目前为止所做的。

Private Sub Worksheet_Change(ByVal Target As Range)
    Dim I As Integer
    I = 1
    Application.EnableEvents = False
    For I = 1 To 20
        Range("A" & I).Value = I
    Next
    Range("A21").Value = ""
    Application.EnableEvents = True
End Sub

1 个答案:

答案 0 :(得分:0)

您可以遍历A列中的每个单元格,如果其值大于(或等于)刚刚更改的单元格,则将其递增1:

Private Sub Worksheet_Change(ByVal Target As Range)
    Dim I As Long
    Dim v As Long
    Dim r As Range
    Set r = Application.Intersect(Range("A:A"), Target)
    If r Is Nothing Then
        Exit Sub
    End If
    If r.Count > 1 Then
        Exit Sub
    End If
    If IsEmpty(r.Value) Then
        Exit Sub
    End If
    I = 1
    v = r.Value
    If Application.CountIf(Range("A:A"), v) > 1 Then ' Only change things if this
                                                     ' value exists elsewhere
        Application.EnableEvents = False
        For I = 1 To Cells(Rows.Count, "A").End(xlUp).Row
            If Cells(I, "A").Address <> r.Address Then
                If IsNumeric(Cells(I, "A").Value) Then ' skip cells that aren't numeric
                    If Cells(I, "A").Value >= v Then
                        Cells(I, "A").Value = Cells(I, "A").Value + 1
                    End If
                End If
            End If
        Next
        Application.EnableEvents = True
    End If
End Sub