排序升序/降序vba excel不工作

时间:2014-12-09 13:09:13

标签: excel vba sorting excel-vba

我正在建立一个宏,根据其值对一系列单元格进行升序/降序排序。   问题是它没有使用以下数据:

11_NR-10.pdf    16_NR-10.pdf    1_NR-10.pdf    6_NR-10.pdf

当我尝试排序时,我得到以下结果:

1_NR-10.pdf    11_NR-10.pdf    16_NR-10.pdf    6_NR-10.pdf

有人知道如何帮助我吗?

代码:

Dim xlSort As XlSortOrder
Dim LastRow As Long

With ActiveSheet

     LastRow = .Cells(.Rows.Count, "A").End(xlUp).Row

     If (.Range("A3").Value > .Range("A" & CStr(LastRow))) Then
         xlSort = xlAscending
     Else
         xlSort = xlDescending
     End If

     .Range("A3:A" & LastRow).Sort Key1:=.Range("A3"), Order1:=xlSort, Header:=xlNo, _
        OrderCustom:=1, MatchCase:=False, Orientation:=xlTopToBottom, _
        DataOption1:=xlSortNormal


End With
ActiveWorkbook.Save

1 个答案:

答案 0 :(得分:0)

我有一个辅助功能。完整未经测试的代码如下:

Public Sub MySuperSort()
    Dim sortType31 As Integer, lastRow As Long

    lastRow = Cells(Rows.Count, 1).End(xlUp).Row

    sortType = ([A3] > Cells(lastRow, 1))
    Call MyOrder(Range(Cells(3, 1), Cells(lastRow, 1)), 1, False)

    ActiveWorkbook.Save
End Sub

Private Sub MyOrder(ByVal tableRange As Range, ByVal columnIndex As Integer, ByVal ascending As Boolean, Optional ByVal header As Boolean = True)
    Dim orderBy As Integer, hasHeader As Integer
    orderBy = IIf(ascending, xlAscending, xlDescending)
    hasHeader = IIf(header, xlYes, xlNo)

    With tableRange.Parent
        .Sort.SortFields.Clear
        .Sort.SortFields.Add _
            Key:=Intersect(tableRange, tableRange.Columns(columnIndex)), _
            SortOn:=xlSortOnValues, Order:=orderBy, DataOption:=xlSortNormal
        With .Sort
            .SetRange tableRange
            .header = hasHeader
            .MatchCase = False
            .Orientation = xlTopToBottom
            .SortMethod = xlPinYin
            .Apply
        End With
    End With
End Sub