【问题标题】:sort ascending/descending vba excel not working排序升序/降序vba excel不起作用
【发布时间】:2014-12-09 22:41:28
【问题描述】:

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

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、11、2、22 等,而不是实际的 1、2、11、22。如果将文件名更改为 01、11、02、22。排序将是 01、02、11、22 .
  • 如果您将这四个文件名放入四个不同的列单元格中并要求 Excel 对它们进行 A-Z 排序,这正是您将获得的排序顺序。然后,您的代码正确的——从某种意义上说,它正在复制 Excel 的电子表格行为。
  • @PaulFrancis 不幸的是我无法更改文件名。它的左侧不能包含任何 0。
  • @FaustoArinosBarbuto 不幸的是,文件名需要在同一列中

标签: vba sorting excel


【解决方案1】:

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

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

【讨论】:

  • 你的意思是:MyOrder (.Range(.Cells(3,1).Cells(lastRow,1), 1, false) ?
  • Call MyOrder(.Range(.Cells(3,1).Cells(lastRow,1), 1, false)
  • 抱歉,这可能看起来很傻,但我在哪里调用 MyOrder?我可以创建一个按钮,然后简单地调用它并传递它的参数吗?
  • 它在 Call MyOrder(.Range(.Cells(3,1).Cells(lastRow,1), 1, false) 上返回语法错误。我会尝试修复它然后我会如果我仍然有问题,请再次发布
  • 忘记了")"。再试一次。
猜你喜欢
  • 1970-01-01
  • 2019-08-08
  • 1970-01-01
  • 2014-05-06
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多