【发布时间】:2020-11-06 18:54:45
【问题描述】:
我有两个日期范围,我试图将它们转换为两个字符串 OldestDate 和 NewestDate。但是,今天我遇到了一个问题,其中一个日期格式为dd/mm/yyyy,另一个日期格式为mm/dd/yyyy
这是我放置在两个单独工作表上的示例数据:注意,我复制了“日期”格式单元格旁边的单元格内容以供视觉参考,但在我的实际数据中,只有“日期”列。
和
这是我用来转换成字符串的代码和调试输出:
Public Sub Get_Date()
DateHeader = "A"
Set rng = Application.ActiveSheet.Range(DateHeader & "1:" & DateHeader & Cells(Rows.Count, 1).End(xlUp).Offset(1).Row)
OldestDate = Format(WorksheetFunction.min(rng), "dd/mm/yyyy")
Debug.Print OldestDate
NewestDate = Format(WorksheetFunction.Max(rng), "dd/mm/yyyy")
Debug.Print NewestDate
'20200908
'Sept 8, 2020
aDate = Split(OldestDate, "/")
If UBound(aDate) = 2 Then
sDay = aDate(0)
If Len(sDay) = 1 Then
sDay = "0" & sDay
End If
sMonth = aDate(1)
If Len(sMonth) = 1 Then
sMonth = "0" & sMonth
End If
sYear = aDate(2)
End If
OldestDateStr = sYear & sMonth & sDay
Debug.Print OldestDateStr
aDate = Split(NewestDate, "/")
If UBound(aDate) = 2 Then
sDay = aDate(0)
If Len(sDay) = 1 Then
sDay = "0" & sDay
End If
sMonth = aDate(1)
If Len(sMonth) = 1 Then
sMonth = "0" & sMonth
End If
sYear = aDate(2)
End If
NewestDateStr = sYear & sMonth & sDay
Debug.Print NewestDateStr
End Sub
控制台/调试:
7/10/2020 ' This is Correct
8/10/2020 ' This is Correct
20201007 ' This is Correct
20201008 ' This is Correct
8/17/2020 ' Incorrect
8/18/2020 ' Incorrect
20201708 ' Incorrect
20201808 ' Incorrect
【问题讨论】:
-
可能数据来源于一个CSV文件,该文件是OPEN的,并且文件中的日期格式与您Windows中的短日期格式不同区域设置。如果是这种情况,似乎格式正确的那个将被错误地解析。数据的来源很重要,因为它将决定相关的修复。
-
两者都来自我从中抓取数据的同一个内部 web 应用程序,但我怀疑您可能是正确的。我发现了一个“解决方法”,因为我不愿意进一步调试。谢谢@RonRosenfeld