简体   繁体   English

我正在使用VBA DateSerial函数分隔字符串中的日期,但是当字符串中的年份为'1000'时,Excel Ends Sub会出现。 我究竟做错了什么?

[英]I am using the VBA DateSerial function to separate dates in a string, but Excel Ends Sub when year in string is '1000'. What am I doing wrong?

I am using the VBA DateSerial function to separate dates in a string, and populate them on another worksheet but Excel Ends Sub when the year in string is '1000'. 我正在使用VBA DateSerial函数将字符串中的日期分开,并在字符串中的年份为'1000'时将它们填充在另一个工作表中,但Excel Ends Sub。

Here is an example: 这是一个例子:

string data:
2012-01-012012-03-01
2013-01-012013-03-01
1000-01-011000-01-01

VBA code:
Private Sub Worksheet_Change(ByVal Target As Range)
    If Not Intersect(Target, Columns(1)) Is Nothing Then
        On Error GoTo Safe_Exit
        Application.EnableEvents = False
        Dim rng As Range, str As String, rw As Long
        For Each rng In Intersect(Target, Columns(1))
            str = rng.Value
            If Len(str) >= 8 Then
                With Sheet2
                    rw = .Cells(Rows.Count, 1).End(xlUp).Offset(1, 0).Row
                    .Cells(rw, 1) = DateSerial(Left(str,4), Mid(str, 6, 2), Mid(str, 9, 2)) 
                    .Cells(rw, 2) = DateSerial(Mid(str, 11, 4), Mid(str, 16, 2), Mid(str, 19, 2)) 
                End With
          End If
        Next rng
    End If
Safe_Exit:
    Application.EnableEvents = True
End Sub

No matter how many strings I paste into the first worksheet, the dates will appear on the second sheet only until a date with the year 1000. What am I doing wrong? 无论我将多少个字符串粘贴到第一个工作表中,日期都只会在第二个工作表上显示,直到日期为1000年为止。我在做什么错了?

Excel bases dates as number of days since midnight 30 December 1899 and does not except negative dates. Excel以日期为基础,即自1899年12月30日午夜以来的天数,并且不包括负日期。

Even though it appears that you can enter dates prior to Jan 1, 1900, if you notice that they will be left-aligned. 即使您似乎可以输入1900年1月1日之前的日期,如果您注意到它们将左对齐。 This indicates that they have been accepted as string values and not a date. 这表明它们已经被接受为字符串值而不是日期。

You could modify your code to set a String value instead. 您可以修改代码以设置String值。 A valid date as a string will automatically be converted to a date. 有效日期作为字符串将自动转换为日期。 .Cells(rw, 1) = Cstr(DateSerial(Left(str,4), Mid(str, 6, 2), Mid(str, 9, 2))) .Cells(rw,1)= Cstr(DateSerial(Left(str,4),Mid(str,6,2),Mid(str,9,2)))

Note that 1/1/1904 could also be the minimum if the 1904 Date option is selected. 请注意,如果选择了1904 Date选项,则1/1/1904也可能是最小值。

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

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