我们有多少次在提供给我们的电子表格中获取日期为 12.26.2016 或 26/12/2016(英国格式),却被告知日期无效或没有 26 月? 本文探索使用 VBA 修复日期,使用 TRIM、LEFT、RIGHT 和 MID 函数。
本文假定读者已显示开发人员功能区并且熟悉 VBA 编辑器。 如果没有,请谷歌“Excel Developer Tab”或“Excel Code Window”。
本练习中的xlsm可以下载 开始.
不是我们的问题!
解决问题最好的地方是源头。 但是,在这种情况下,再多的说服也无法说服薪资部门 12.26.1994 不是有效日期(除非在某些东欧国家/地区的计算机控制面板中如此配置)。
事实上我们可以证明它不是机器可读的。 例如,将日期加 7 天:
"=01.01.2017 + 7" = #VALUE. "=2017.01.01 + 7" = #VALUE.
然而…
"=2017-01-01 + 7" = 2017/01/08.
让我们假设他们认为这不是他们的问题。
日期格式
我们必须确定的第一件事是日期是美国格式还是国际格式。
我们的示例清楚地表明我们正在查看美国用法,即 MDY 而不是国际格式 DMY。
确定来源后,我们需要更改数据格式,以便 Excel 可以理解它们,无论是在国际上还是在美国。
执行此操作的最佳方法是将日期更改为 yyyymmdd,这是一种不需要限定的格式。
流程
我们将循环遍历文档中的每一行,调用一个函数根据来源国家“更正”日期。 更正日期后,我们将计算员工的年龄。
守则
将以下代码复制到新模块中:
Option Explicit
Sub Main()
Dim strNewFormat As String
Dim strDate As String
Sheets("Main").Range("B4").Select
'Cycle through the sheet rows, using IDNumber as an anchor
'to prevent a premature halt caused by a blank date of birth
Do While ActiveCell > ""
If ActiveCell.Offset(0, 2) > "" Then
strDate = ActiveCell.Offset(0, 2)
'Remove leading or trailing spaces
strDate = Trim(strDate)
'Call the function
strNewFormat = ReformatDate(strDate, "USA")
'Write the result from the function ReformatDate to a new column
ActiveCell.Offset(0, 3) = strNewFormat
'Determine age by subtracting the previous column from today's date
ActiveCell.Offset(0, 4) = "=(NOW()-RC[-1])/365.25"
'Convert to intger, thus lopping off decimal places
ActiveCell.Offset(0, 4) = Int(ActiveCell.Offset(0, 4))
End If
Range("B" & ActiveCell.Row + 1).Select
Loop
End Sub
Function ReformatDate(sDate As String, sSource As String)
Dim yyyy, mm, dd As String
yyyy = Right(sDate, 4)
If sSource = "USA" Then
mm = Left(sDate, 2)
dd = Mid(sDate, 4, 2)
Else
mm = Mid(sDate, 4, 2)
dd = Left(sDate, 2)
End If
ReformatDate = yyyy & "-" & mm & "-" & dd
End Function
向您的表单添加一个按钮,并将其分配给 Sub Main。
买者
在向您的模块添加太多复杂代码之前,请注意 Excel 在主要应用程序开发中并不总是稳定的,并且通常无法自行恢复损坏的代码。 结果可能是您唯一的副本损坏,因为损坏发生在“保存”中。
经常备份并使用工具修复 Excel文件损坏.
作者简介:
Felix Hooker 是一位数据恢复专家 DataNumen, Inc.,它是数据恢复技术领域的世界领先者,包括 修复 rar 文件损坏 和sql恢复软件产品。 欲了解更多信息,请访问 datanumen.com
