excel自动按字母顺序排列

时间:2013-11-24 22:29:30

标签: excel excel-vba vba

人们,我的疑惑很简单..我在excel中创建了一个包含多个字段的电子表格,例如:

NAME       ADDRESS      PHONE
carlos      ave. 1    12345678
Argeu       av .2     87654321

在此之后,我在模块中使用了以下代码:

Private Sub Worksheet_Activate()
ActiveSheet.ScrollArea = "$A$2:$A$300"
End Sub


Private Sub Worksheet_Change(ByVal Target As Range)
If Target.Count > 1 Then Exit Sub
If Target.Column <> 1 Then Exit Sub
Dim LR As Long
LR = Cells(Rows.Count, "A").End(xlUp).Row
Range("$A$2:$A" & LR).Sort Key1:=Range("$A$2")
End Sub

这个代码将在示例表中,Argeu站在卡洛斯上,到目前为止一直很好,但我想当Argeu从卡洛斯手机和地址数据上升时... 如果有人可以提供帮助,谢谢

1 个答案:

答案 0 :(得分:0)

如果您想要对Col C进行排序,那么也要在排序范围中包含它。看到这个。

更改

Range("$A$2:$A" & LR).Sort Key1:=Range("$A$2")

Range("$A$2:$C" & LR).Sort Key1:=Range("$A$2")

修改

您的代码可以正确地重写为

Private Sub Worksheet_Change(ByVal Target As Range)
    On Error GoTo Whoa

    Application.EnableEvents = False

    '~~> For xl2007+ use .CountLarge
    If Target.Cells.CountLarge > 1 Then Exit Sub
    '~~> For xl2003 use .Count
    'If Target.Cells.Count > 1 Then Exit Sub

    Dim LR As Long

    If Application.WorksheetFunction.CountA(Cells) <> 0 Then
        LR = Cells.Find(What:="*", _
                      After:=Range("A1"), _
                      Lookat:=xlPart, _
                      LookIn:=xlFormulas, _
                      SearchOrder:=xlByRows, _
                      SearchDirection:=xlPrevious, _
                      MatchCase:=False).Row
    Else
        LR = 1
    End If

    Range("$A$2:$C" & LR).Sort Key1:=Range("$A$2")

Letscontinue:
    Application.EnableEvents = True
    Exit Sub
Whoa:
    MsgBox Err.Description
    Resume Letscontinue
End Sub

<强>截图

enter image description here