我正在尝试创建一个代码,当我在底部添加新值或更改现有值时,会自动对列进行排序。所以我的价值范围从E3:E210;如果我在E211添加或更改值。我希望它自动排序该范围(E3:E210)或者如果我在E205更改值。我也希望它转到它被分类到的单元格(如果可能的话)。所以,如果我在E211添加一个值,它会说是E150。我希望它选择那个单元格,所以我基本上都呆在那个单元格上。
这是我在工作表上运行的所有代码:
Private Sub Worksheet_SelectionChange(ByVal Target As Range)
Dim Rng As Range
Set Rng = Range(Cells(3, 6), Cells(500, 7))
Dim Intersection
Set Intersection = Application.Intersect(Target, Rng)
If Target.Cells.Count = 1 Then
If Not Intersect(Target, [B2]) Is Nothing Then _
Range("E:E").Find(vbNullString, [E3], , , , xlNext).Select
End If
If Not Intersection Is Nothing Then
If IsNumeric(Selection.Value) And Selection.Value <> "" Then
If (GetAsyncKeyState(vbKeyRButton)) Then 'right mouse button
Selection.Value = (Selection.Value + 1)
Cells(Selection.Row, 1).Select
End If
End If
End If
End Sub
Private Sub Worksheet_BeforeRightClick(ByVal Target As Range, Cancel As Boolean)
Dim Rng As Range
Set Rng = Range(Cells(3, 6), Cells(500, 7))
Dim Intersection
Set Intersection = Application.Intersect(Target, Rng)
If Not Intersection Is Nothing Then
Cancel = True
End If
End Sub
Private Sub Worksheet_Change(ByVal Target As Range)
Target.EntireColumn.Sort Key1:=Target, Order1:=xlAscending, Header:=xlGuess, OrderCustom:=1, MatchCase:=False, Orientation:=xlTopToBottom
End Sub
最后一部分是我尝试进行自动排序(在论坛的帮助下)。它会对值进行排序。但它并没有对某个范围进行排序,也不会停留在单元格上。如果有人可以提供帮助,非常感谢!
答案 0 :(得分:1)
如果要自动对列中的任何更改进行排序,请执行以下操作:
Option Explicit
Private Sub Worksheet_Change(ByVal Target As Range)
Dim myRng As Range
Dim S As String
Set myRng = Cells.Columns(5) '<--change to column you want to sort
If Not Intersect(Target, myRng) Is Nothing Then
Application.EnableEvents = False
S = Target.Text
myRng.Resize(columnsize:=3).Sort key1:=myRng, order1:=xlAscending, Header:=xlNo, Orientation:=xlSortColumns
myRng.Find(what:=S, LookIn:=xlValues, lookat:=xlWhole, MatchCase:=True).Select
Selection.Show
Application.EnableEvents = True
End If
End Sub
(我不完全确定.Show语句是必需的。)
编辑:已更改为将E:G排在一起