更改date格式VBA
我有一个date列,看起来像这样:
04-03-2013 01:57:32 PM IST
我试图改变它看起来像这样:
04/03/2013 13:57:32
我的代码:
Columns("D:E").Select Selection.Replace What:=" IST", Replacement:="", LookAt:=xlPart, _ SearchOrder:=xlByRows, MatchCase:=False, SearchFormat:=False, _ ReplaceFormat:=False Selection.Replace What:=" IDT", Replacement:="", LookAt:=xlPart, _ SearchOrder:=xlByRows, MatchCase:=False, SearchFormat:=False, _ ReplaceFormat:=False Selection.Replace What:="-", Replacement:="/", LookAt:=xlPart, _ SearchOrder:=xlByRows, MatchCase:=False, SearchFormat:=False, _ ReplaceFormat:=False
问题是它改变它看起来像这样:
04-03-2013 01:57:32 PM
只有当我在“PM”之后按下ENTER键时,它才会变成:
04/03/2013 13:57:32
我怎样才能自动做到这一点?
我想你只需要指定所需的数字格式:
Selection.NumberFormat = "dd/mm/yyyy hh:mm:ss" ' or mm/dd/yyyy, not sure which you want!
如果您想将原始date转换为如上格式化的“真实”Exceldate,那么请在常规模块中尝试:
Option Explicit Sub ChangeDateTimeFormat() Dim Rng As Range Dim C As Range Set Rng = Range("D:E").SpecialCells(xlCellTypeConstants) For Each C In Rng With C If Right(.Text, 4) = " IDT" Or Right(.Text, 4) = " IST" Then .Value = DateValue(Left(.Text, Len(.Text) - 4)) + TimeValue(Left(.Text, Len(.Text) - 4)) .NumberFormat = "mm/dd/yyyy hh:mm:ss" End If End With Next C End Sub
这只是在MDY格式的date进行testing。 如果你的date是DMY格式,这不起作用,我会进一步testing。