EXCEL 上的 VBA/自动排序帮助

EXCEL 上的 VBA/自动排序帮助

我正在尝试编写 VBA 代码,以便当我自动将值输入表格时,这些值会自动排序。它对某些图表有效,但现在只有最后一张图表会自动排序,其他图表均不会自动排序。我已附上我的代码。代码

答案1

Private Sub Worksheet_Change(ByVal Target As Range)
    Dim SortRange As Range
    Dim KeyRange As Range

    ' Set the range to be sorted
    Set SortRange = Me.Range("A2:C" & Me.Cells(Me.Rows.Count, "A").End(xlUp).Row)

    ' Set the range that contains the sort key (e.g., column A)
    Set KeyRange = Me.Range("A2:A" & Me.Cells(Me.Rows.Count, "A").End(xlUp).Row)

    ' Check if the changed range intersects with the sort range
    If Not Application.Intersect(Target, SortRange) Is Nothing Then
        ' Disable events to prevent infinite loop
        Application.EnableEvents = False
    
        ' Sort the range based on the key range
        SortRange.Sort Key1:=KeyRange, Order1:=xlAscending, Header:=xlYes
    
        ' Enable events again
        Application.EnableEvents = True
    End If
End Sub

现在,无论何时在指定范围(A2:C)内输入新数据,工作表都会根据第一列(A 列)自动排序。

相关内容