在Excel中进行数据更新后对范围进行排序

时间:2012-03-09 14:52:28

标签: excel excel-vba vba

我在excel中有一个表,可以通过从网站上拉动来自动(或手动)更新。

我有另一个链接的表,我希望每次更新数据时自动排序。有什么办法吗?

1 个答案:

答案 0 :(得分:2)

在需要自动更新的表所在的工作表中,您可以添加类似下面的代码(伪代码) - 它会在每次更改时对表进行排序。请注意,如果您经常更新,它可能会变慢。

Private Sub Worksheet_Change(ByVal Target As Range)
    If Target is in the table (you can check Target.Row and Target.Column for example) Then
        Sort the table
    End If
End Sub

如果范围是名为named_range的命名范围,您可以这样做(效率不高但可读):

Private Sub Worksheet_Change(ByVal Target As Range)
    For Each c In [named_range]
      If c = Target Then MsgBox "OK"
    Next c
End Sub

或者你可以做到这一点,如果命名范围很大,性能会更好:

Private Sub Worksheet_Change(ByVal Target As Range)
    Dim row_start As Long
    Dim row_end As Long
    Dim col_start As Long
    Dim col_end As Long

    row_start = [named_range].Cells(1, 1).Row
    col_start = [named_range].Cells(1, 1).Column
    row_end = row_start + [named_range].Rows.Count - 1
    col_end = col_start + [named_range].Columns.Count - 1

    If Target.Row >= row_start And Target.Row <= row_end And Target.Column >= col_start And Target.Column <= col_end Then
      MsgBox "In range"
    End If

End Sub