如何在Excel中标准化数据格式

我从许多工作簿收集数据。 问题是,在每个文档中,date格式不一致:2015年1月16日2015年1月6日24.03.2014

我想实现的是“YYYY-MM-DD”格式。 在我的代码中,我有一个负责清除date列的情况。 现在我越来越绝望了,我在代码中join了愚蠢的date格式,但是对于虚线格式(上面的粗体)却没有改变。 即使我手动select列并更改格式types,或将值复制到.txt文件,然后将其复制回原始图纸,也尝试使用新的工作簿,但没有任何事情发生。 为什么在这几个例子中改变date值是不可能的? 任何帮助,将不胜感激。 这里是代码:

Case 6: sourceWorkbook.Activate sourceWS.Activate sourceWS.Columns(i).Select Selection.NumberFormat = "YYYY-MM-DD;@" sourceWS.Range(Cells(2, i), Cells(lastrw, i)).NumberFormat = "YYYY-MM-DD;@" For j = startRow To lastrw Step 1 'Assign the header to the first row NewWorksheet.Cells(1, i) = sourceWS.Cells(startRow, i).Value On Error Resume Next textToFormat = CStr(sourceWS.Cells(j, i).Value) d = CDate(textToFormat) finalDate = Format(textToFormat, "YYYY-MM-DD") NewWorksheet.Cells(j - adjustRows, i) = finalDate 'This error handler purpose to handle the header name! If Err Then NewWorksheet.Cells(j - adjustRows, i) = textToFormat End If On Error GoTo 0 Next j Set fckFormat = NewWorksheet.Columns(i) fckFormat.NumberFormat = "YYYY-MM-DD;@" NewBook.Activate NewWorksheet.Activate NewWorksheet.Columns(i).Select Selection.NumberFormat = "YYYY-MM-DD;@" 

正如约旦所build议的那样,问题是这些数据被格式化为string而不是date。 例如,如果我在一个新的工作簿中input上述每个date,则前两个date被正确检测为date(可以格式化),而最后一个date被视为文本string。 这可能会根据您的区域设置而有所不同。

不幸的是,CDatefunction也没有认识到这种格式是有效的date。 尝试运行以下,你会得到一个types不匹配的错误:

 MsgBox CDate("24.03.2016") 

您可以使用replace方法将其转换为有效date,方法是用斜线replace点:

 Set datecol = Sheets(1).Columns(1) datecol.Replace What:=".", Replacement:="/", LookAt:=xlPart, _ SearchOrder:=xlByRows, MatchCase:=False, SearchFormat:=False, _ ReplaceFormat:=False 

单元格将仍然被格式化为一个string,但是现在可以使用现有的循环将其转换为使用CDate的date:

  d = CDate(textToFormat) NewWorksheet.Cells(j - adjustRows, i) = d 

NumberFormat然后将正确工作。

注:我会build议使用CDate而不是格式,以便date仍然存储为值而不是文本。