将文本date格式化为Excel可用的date格式

我有一个Excel格式的date格式为“2016年3月6日”,我想转换为“d / MM / yyyy”或“6/3/2016”为了使用像DATEVALUE()提取date的部分。

我写了一个小的macros来帮助我,这只是在input数据集中手动replacedate。

 Sub MonthReplace() Dim res As Boolean Dim i As Long Dim monthArray As Variant monthArray = Array("January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December") For i = LBound(monthArray) To UBound(monthArray) res = Range("RawDataset").Replace(" " + monthArray(i) + ", ", "/" + Format(i + 1) + "/") Next i End Sub 

结果是一个不稳定的数据集。 请参阅前后的图像。

之前 后

有些正在得到正确的转换,而另一些正在得到他们的月份和date互换。 当我用来replace不使用macros的月份时不会发生此行为。 Excel中的默认date格式按照我所需的格式进行设置。

系统区域设置date:

日期设置

也许直接CDate方法将为你工作,因为你的系统和Excel语言似乎是英语。 对我来说,这是行不通的,因为我的系统不知道英文月份名称。 所以我必须真正用数字来代替它们:

 Sub MonthReplace() Dim i As Long Dim monthArray As Variant Dim c As Range Dim strDate As String monthArray = Array("January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December") For Each c In Range("RawDataset") strDate = Replace(c.Value, " ", "") strDate = Replace(strDate, ",", "") For i = LBound(monthArray) To UBound(monthArray) strDate = Replace(strDate, monthArray(i), "/" & (i + 1) & "/", , , vbTextCompare) If IsDate(strDate) Then Exit For Next i If IsDate(strDate) Then c.Value = CDate(strDate) Next End Sub 

转换每个单元格可能更可靠:

 For Each Row In Range("RawDataset").Rows Row.Cells(1, 2) = CDate(Row.Cells(1, 1)) Next 

在尝试了各种方法后,终于在06 March, 2016 06-March-2016 06 March, 2016了这个转换06 March, 2016使其可以在Excel中使用(我的主要目标),明确说明月份以避免VBAdate格式问题。

 Sub MonthReplace() Dim res As Boolean Dim i As Long Dim endRow As Long Dim columnArray As Variant ' only work on columns containing the dates columnArray = Array("W", "X", "Y", "Z", "AA", "AB", "AC", "AD", "AE", "AF", "AL", "AM") ' find the last cell with data in the current sheet endRow = ActiveCell.SpecialCells(xlLastCell).Row For i = LBound(columnArray) To UBound(columnArray) With Range(columnArray(i) & "3:" & columnArray(i) & endRow) res = .Replace(", ", "-") res = .Replace(" ", "-") End With Next i End Sub 

另外,在+ Axel Richter的回答中,通过检查Cell.Value错误并确保最后4个字符是数字,我写了以下内容。 但是,由于每个单元格都被检查,所以这种方法非常慢。 可以使用上述策略(范围内的选定列)来提高速度。

 Sub MonthReplace_slow() Dim i As Long Dim monthArray As Variant Dim c As Range Dim strDate As String monthArray = Array("January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December") For Each c In Range("RawDataset") strDate = "" If Not IsError(c.Value) Then strDate = c.Value If IsNumeric(Right(strDate, 4)) Then strDate = Replace(strDate, " ", "") strDate = Replace(strDate, ",", "") For i = LBound(monthArray) To UBound(monthArray) strDate = Replace(strDate, monthArray(i), "/" & (i + 1) & "/", , , vbTextCompare) If IsDate(strDate) Then Exit For Next i If IsDate(strDate) Then c.Value = CDate(strDate) End If End If Next End Sub 

我没有与其他CDate方法玩。