[英]Sorting Alphabetically using VBA from row 5 onwards
我試圖找出如何使數據庫自動使用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行。 我知道我想念什么,但是看不到我想念的是什么!
請不要誤用OERN(下一步恢復錯誤)。 就像告訴代碼關閉:)。 正確處理錯誤。
另一個有趣的讀物
這是您要嘗試的嗎?
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
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.