2017-02-14 131 views
1

我正在从许多工作簿中收集数据。问题是,每个文件中的日期格式并不一致: 16/01/2015 2015年1月6日 2014年3月24日如何在excel中实现数据格式的标准化

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

 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;@" 
+0

[太多不同的单元格格式]的可能重复(http://stackoverflow.com/questions/2449755/too-many-different-cell-formats) – R3uK

+0

查看答案开始:**许多人似乎遇到这个问题。** – R3uK

+0

@ R3uK,你的意思是在源表或代码中?我测试了其他格式的代码,除了提到的代码。 – simpleMan

回答

0

正如约旦所说,问题是这个数据被格式化为一个字符串而不是日期。例如,如果我在新工作簿中输入上述每个日期,则前两个日期会被正确检测为日期(并可以格式化),而最后一个日期会被视为文本字符串。这可能会根据您的区域设置而有所不同。

不幸的是,CDate功能也无法将此格式识别为有效日期。尝试运行以下,你会得到一个类型不匹配错误:

MsgBox CDate("24.03.2016") 

您可以使用替换法在将它转换为有效的日期,用斜杠替换点:

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

细胞仍然会被格式化为一个字符串,但您现在可以使用现有的循环将其转换为使用CDATE日期:然后

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

NumberFormat的将正常工作。

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