2014-12-09 147 views
0

我正在構建一個宏,根據它的值升序/降序一系列單元格。 的問題是,它不與下面的數據工作:按升序/降序排序vba excel不工作

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

那麼排序工作正常。字母排序是1,11,2,22等,而不是現實的1,2,11,22。如果您將文件名更改爲01,11,22,22。排序爲01,02,11,22 – PaulFrancis 2014-12-09 13:18:03

+0

如果您將這四個文件名放入四個不同的列單元格並要求Excel對它們進行排序,那麼這就是您將得到的排序順序。然後,您的代碼是正確的 - 就是說,它正在複製Excel的電子表格行爲。 – 2014-12-09 13:22:19

+0

@PaulFrancis不幸的是我不能改變文件名。它不能在左側包含任何0。 – 2014-12-09 13:25:25

回答

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 
+0

您的意思是:MyOrder(.Range(.Cells(3,1).Cells(lastRow,1),1,false)? – 2014-12-09 13:28:40

+0

是'Call MyOrder .Range(.Cells(3,1).Cells(lastRow,1),1,false)' – Makah 2014-12-09 13:31:20

+0

對不起,它可能看起來很傻,但我在哪裏調用MyOrder?我可以創建一個按鈕,然後簡單地調用它傳遞它的參數? – 2014-12-09 13:43:58