我写了一个Sub来使用Application.WorksheetFunction
对日期进行排序。它从工作表的第一列获取日期,并将它们写入第二列。之后,它将它们分成几年,并从它们中创建一个写入Cell (1,3)
的字符串。所有工作都正常,但第二栏中的第一个日期始终为' 30-12-1899'。怎么可能?
Function dzien(data As String) As String
Select Case Day(data)
Case Is < 10
dzien = "0" & CStr(Day(data))
Case Is >= 10
dzien = CStr(Day(data))
End Select
End Function
Function miesiac(data As String) As String
Select Case Month(data)
Case Is < 10
miesiac = "0" & CStr(Month(data))
Case Is >= 10
miesiac = CStr(Month(data))
End Select
End Function
Sub Sortuj_daty()
Dim wb As Workbook
Dim ws As Worksheet
Set wb = ActiveWorkbook
Set ws = wb.Worksheets(1)
Dim i As Long
Dim j As Long
Dim k As Long
Dim daty() As String
Dim daty_int() As Long
Dim daty_uporzadkowane() As String
Dim daty_calk As String
Dim wiersz As Integer
wiersz = 0
Do
wiersz = wiersz + 1
ReDim daty(wiersz)
ReDim daty_int(wiersz)
ReDim daty_uporzadkowane(wiersz)
Loop Until ws.Cells(wiersz + 1, 1).Value = "" Or ws.Cells(wiersz + 1, 1).Value = 0
ReDim daty_uporzadkowane(wiersz + 1)
daty_calk = ""
For i = 0 To UBound(daty) - 1
daty(i) = ws.Cells(i + 1, 1).Value
daty_int(i) = CDbl(CDate(Format(daty(i), "yyyy-mm-dd")))
Next i
For j = 0 To UBound(daty) - 1
daty_uporzadkowane(j) = CDate(Application.WorksheetFunction.Small(daty_int, j + 1))
ws.Cells(j + 1, 2) = daty_uporzadkowane(j)
Next j
k = 0
daty_uporzadkowane(UBound(daty_uporzadkowane) - 1) = #1/1/1900#
Do
Do
k = k + 1
If k = 1 Then k = k - 1
End If
daty_calk = daty_calk & CStr(dzien(daty_uporzadkowane(k))) & "-" & miesiac(daty_uporzadkowane(k)) & "/"
Loop Until Year(CDate(daty_uporzadkowane(k))) < Year(CDate(daty_uporzadkowane(k + 1))) Or k = UBound(daty) - 1
daty_calk = Left(daty_calk, Len(daty_calk) - 1) & "-"
daty_calk = daty_calk & Year(daty_uporzadkowane(k)) & " / "
Loop Until k = UBound(daty) - 1
daty_calk = Left(daty_calk, Len(daty_calk) - 3)
ws.Cells(1,3).Value = daty_calk
End Sub
答案 0 :(得分:0)
VBA将1
解释为1899年的最后一天。
因此,具有更多幻想的0
是30.12.1899。如果将空单元解析为数字,则将其视为0。在您的情况下,您在排序范围内的某个位置是一个空单元格。
在一个新的excel文件中运行这一小段代码,你就可以得到它:
Public Sub TestMe()
Debug.Print CDate(1)
Range("A1").ClearContents
Debug.Print Year(Range("A1")); Month(Range("A1")); Day(Range("A1"))
Debug.Print Format(0, "yyyy-mm-dd") '1899-12-30
End Sub