Private Sub Worksheet_Change(ByVal Target As Range)
[COLOR="DarkGreen"]' This routine runs every time a change is made on Sheet1[/COLOR]
[COLOR="DarkGreen"]' If a name is typed in the next empty cell, then the range[/COLOR]
[COLOR="DarkGreen"]' of names is sorted top to bottom. If any other cell is[/COLOR]
[COLOR="DarkGreen"]' changed, then nothing happens.[/COLOR]
[COLOR="DarkGreen"]' Pre-condition:[/COLOR]
[COLOR="DarkGreen"]' - Need to have set in a module a public range variable named rNextEmptyCell[/COLOR]
[COLOR="DarkGreen"]' - Need to have added in that same module a subroutine named SetNextEmptyCell[/COLOR]
[COLOR="DarkGreen"]' which sets the public variable accordingly (see code elsewhere)[/COLOR]
[COLOR="DarkGreen"]' Handle the condition when this is the first change on the sheet and[/COLOR]
[COLOR="DarkGreen"]' the public variable pointing to the next empty cell has not yet been set[/COLOR]
If rNextEmptyCell Is Nothing Then
[COLOR="DarkGreen"]' Set variable pointing to next empty cell (i.e., first time through)[/COLOR]
Call SetNextEmptyCell
[COLOR="DarkGreen"]' If this is the first time through and the Target cell[/COLOR]
[COLOR="DarkGreen"]' would have been the next empty cell, then set the next[/COLOR]
[COLOR="DarkGreen"]' empty cell range to be the Target cell[/COLOR]
If Target.Column = rNextEmptyCell.Column And _
rNextEmptyCell.Row - Target.Row = 1 Then _
Set rNextEmptyCell = Target
End If
[COLOR="DarkGreen"]' Handle the condition when cells have been deleted[/COLOR]
If rNextEmptyCell.Offset(-1, 0) = "" Then _
Call SetNextEmptyCell
[COLOR="DarkGreen"]' Compare the Target range for the change event to the next empty cell[/COLOR]
Dim isect As Range
Set isect = Application.Intersect(rNextEmptyCell, Target)
[COLOR="DarkGreen"]' If they are the same, run this routine; if not, skip it[/COLOR]
If Not isect Is Nothing Then
[COLOR="DarkGreen"]' Declare variables just so this code makes more sense[/COLOR]
Dim rFirstDataCell As Range
Dim rSortRange As Range
[COLOR="DarkGreen"]' Point to first cell to be sorted (i.e., A2)[/COLOR]
Set rFirstDataCell = Cells(2, 1)
[COLOR="DarkGreen"]' Set range to be sorted (i.e., A2 all the way to the bottom)[/COLOR]
Set rSortRange = Range(rFirstDataCell, rFirstDataCell.End(xlDown))
[COLOR="DarkGreen"]' Perform the sort, top to bottom[/COLOR]
rSortRange.Sort Key1:=rFirstDataCell, Order1:=xlAscending, Header:=xlGuess, _
OrderCustom:=1, MatchCase:=False, Orientation:=xlTopToBottom, _
DataOption1:=xlSortNormal
[COLOR="DarkGreen"]' Set public range variable pointing to next empty cell[/COLOR]
Call SetNextEmptyCell
[COLOR="DarkGreen"]' Clean up[/COLOR]
Set rFirstDataCell = Nothing
Set rSortRange = Nothing
End If
[COLOR="DarkGreen"]' Clean up[/COLOR]
Set isect = Nothing
End Sub