简体   繁体   English

如何对日期数据类型进行排序?

[英]How to sort date data type?

I've been trying to sort dates on A1 but it sorts based on text not the value我一直在尝试对 A1 上的日期进行排序,但它是根据文本而不是值进行排序的

Private Sub sortData()

Worksheets(Me.Combobox1.Value).Range("A1:F1", Range("A1:F1").End(xlDown)).Sort
 Key1:=Range("A1"), Order1:=xlAscending, Header:=xlYes
End Sub

在此处输入图像描述

As @Marcelo Scofano Diniz started to say, when you run into a problem forget about the shortcxuts and go by the book.正如@Marcelo Scofano Diniz 开始说的那样,当您遇到问题时,请忘记本书中的 shortcxuts 和 go。 Here is the book.这里是书。

Private Sub SortByDate()
    
    Dim Ws              As Worksheet
    Dim SortRange       As Range
    
    Set Ws = Worksheets(Me.ComboBox1.Value)
    With Ws
        Set SortRange = .Range(.Cells(1, 1), .Cells(.Rows.Count, "A").End(xlUp)) _
                        .Resize(, 6)
        With .Sort.SortFields
            .Clear
            .Add2 Key:=SortRange.Cells(1), _
                  SortOn:=xlSortOnValues, _
                  Order:=xlAscending, _
                  DataOption:=xlSortNormal
        End With
        
        With .Sort
            .SetRange SortRange
            .Header = xlYes
            .MatchCase = False
            .Orientation = xlTopToBottom
            .SortMethod = xlPinYin
            .Apply
        End With
    End With
End Sub

The above code will carry out the sort you say your code won't do.上面的代码将执行您说您的代码不会执行的排序。 If the dates are true dates they will be sorted by date.如果日期是真实日期,它们将按日期排序。 If they are fake dates they will be sorted as text.如果它们是假日期,它们将被分类为文本。 And if you have doubt about any part of the code you can see what is being done and step through it line by line.如果您对代码的任何部分有疑问,您可以查看正在执行的操作并逐行执行。

Change The Range to Table of Name Tbl then Create:将范围更改为名称 Tbl 表,然后创建:

Sub Table_Sort(byval FieldNo as Integer)
    Tbl.Sort.SortFields.Clear
    FieldRange(FieldNo).Select
       Tbl.Sort.SortFields.Add _
   Key:=FieldRange(FieldNo), SortOn:=xlSortOnValues, Order:= _
   xlAscending, DataOption:=xlSortNormal

   With Tbl.Sort

   .Header = xlYes
   .MatchCase = False
   .Orientation = xlTopToBottom
   .SortMethod = xlPinYin
   .Apply
   
   End With

End Sub

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

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