简体   繁体   English

排序升/降VBA Excel不起作用

[英]sort ascending/descending vba excel not working

I'm building a macro that sort ascending/descending a range of cells according to its values. 我正在构建一个宏,该宏根据其值对一系列单元格进行升/降序排序。 The problem is that it is not working with the following data: 问题在于它不能使用以下数据:

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

When I try to sort, I get the following result: 当我尝试排序时,得到以下结果:

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

Does someone knows how to help me? 有人知道如何帮助我吗?

Code: 码:

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

I have an auxiliar function just for this. 我为此有一个辅助功能。 Full untested code below : 完整的未经测试的代码如下:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM