gpt4 book ai didi

arrays - 如何在vba中对数组中的日期进行排序?

转载 作者:行者123 更新时间:2023-12-02 05:23:01 25 4
gpt4 key购买 nike

您好,我是编程新手,刚刚开始学习 Excel 的 VBA。我有一个关于数组排序的疑问。如何对包含日期的数组进行排序?例如,如果我有一个包含日期的数组(“23-jul-13”、“11-jan-10”、“1-may-09”、“3-feb-04”),如何对该数组进行排序。我在互联网上搜索了答案,但只能找到用于对数字进行排序的代码。我已经绞尽脑汁想了两天了,但似乎没有得到它。

谢谢

我有下面的代码,它从选定的列中获取日期,但每当我运行它时都会收到错误。我已经想弄清楚这两天出了什么问题。我之前没有提到这段代码,因为我认为它会不必要地增加困惑。子 GetUniqueAndCount 工作正常,但问题在于排序子,因为它不接受作为参数传递给它的数组。

Sub GetUniqueAndCount()
Dim d As Object, c As Range, k, tmp As String

Set d = CreateObject("scripting.dictionary")
'I will select the column of dates
For Each c In Selection
tmp = Trim(c.Value)
If Len(tmp) > 0 Then
If Year(DateValue(Format(tmp, "dd-mmm-yy"))) = 2013 Then
d(tmp) = d(tmp) + 1
End If
End If
Next c
i = 0
ReDim ThisArray(UBound(d.keys)) As Date
For Each k In d.keys
ThisArray(i) = DateValue(Format(k, "dd-mmm-yy"))
i = i + 1

Next k
Sort (ThisArray)
End Sub


Sub Sort(arr() As Date)

Dim Temp As Date
Dim i As Long
Dim j As Long

For j = 2 To UBound(arr)

Temp = arr(j)
For i = j - 1 To 1 Step -1
If (arr(i) <= Temp) Then GoTo 10
arr(i + 1) = arr(i)

Next i
i = 0
10 arr(i + 1) = Temp


Next j
End Sub

最佳答案

您的Sort(arr() As Date)工作正常。问题出在这一行

Sort (ThisArray)

更改为

Sort ThisArray

此外,由于您将 Dates 存储在 ThisArray 中,我希望您已将其声明为 Date

示例

Sub Sample()
Dim ThisArray(1 To 5) As Date

ThisArray(1) = #12/13/2013#
ThisArray(2) = #12/13/2012#
ThisArray(3) = #12/13/2015#
ThisArray(4) = #12/13/2014#
ThisArray(5) = #12/13/2016#

SortAr ThisArray

For i = 1 To 5
Debug.Print ThisArray(i)
Next i
End Sub

Sub SortAr(arr() As Date)
Dim Temp As Date
Dim i As Long, j As Long

For j = 2 To UBound(arr)
Temp = arr(j)
For i = j - 1 To 1 Step -1
If (arr(i) <= Temp) Then GoTo 10
arr(i + 1) = arr(i)
Next i
i = 0
10: arr(i + 1) = Temp
Next j
End Sub

输出

13/12/2012 
13/12/2013
13/12/2014
13/12/2015
13/12/2016

关于arrays - 如何在vba中对数组中的日期进行排序?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20721489/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com