我试图找出如何让数据库在A列中使用VBA按字母顺序自动排序。听起来很简单,但我在前4行中有标题,并希望它从第5行向下排序。我一直在寻找能够找到这样做的代码。我最接近的是使用此代码 -
Private Sub Worksheet_Change(ByVal Target As Range)
On Error Resume Next
If Not Intersect(Target, Range("A:A")) Is Nothing Then
Range("A1").Sort Key1:=Range("A2"), _
Order1:=xlAscending, Header:=xlYes, _
OrderCustom:=1, MatchCase:=False, _
Orientation:=xlTopToBottom
End If
End Sub
问题是当我尝试更改线路时
Range("A1").Sort Key1:=Range("A2"), _
到Range("A5").Sort Key1:=Range("A6"), _
当我测试它时,它仍按行预定排序到第2行而不是第5行。我知道我错过了一些东西,但却看不出我错过了什么!
答案 0 :(得分:0)
请不要滥用OERN(On Error Resume Next)。这就像告诉代码闭嘴:)。正确处理错误。
这是你在尝试的吗?
Private Sub Worksheet_Change(ByVal Target As Range)
Dim lRow As Long
On Error GoTo Whoa
'~> Find the last row in Col A
lRow = Range("A" & Rows.Count).End(xlUp).Row
'~~> Check if it is greater than row 4
If lRow > 4 Then
Application.EnableEvents = False
'~~> Check if the change happened in the relevant range
If Not Intersect(Target, Range("A5:A" & lRow)) Is Nothing Then
'~~> Sort only the relevant range
Range("A4:A" & lRow).Sort Key1:=Range("A4"), _
Order1:=xlAscending, _
Header:=xlYes, _
OrderCustom:=1, _
MatchCase:=False, _
Orientation:=xlTopToBottom, _
DataOption1:=xlSortNormal
End If
End If
Letscontinue:
Application.EnableEvents = True
Exit Sub
Whoa:
MsgBox Err.Description
Resume Letscontinue
End Sub