如何使用macros在Excel中编辑date列以将其格式设置为“dd / mm / yyyy”

这个问题与date和时间有关。 我试图在excel中创build一个macros来编辑date列,以将之前input的所有date更改为通用格式“dd / mm / yyyy”。 但是当date用“。”分隔时 或“ – ”不是被识别为date。 尝试将分隔符replace为“/”,然后从右向左考虑date。 我试过的macros如下:

Sub Date_Edit() Columns("C:C").Select Selection.Insert Shift:=xlToRight Sheets(1).Range("B1:B1000").Replace ".", "/" For i = 2 To 1000 d = Cells(i, 2).Value a = CDate(d) Cells(i, 3) = FormatDateTime(d, 2) Next i Columns("C:C").Select Selection.NumberFormat = "dd/mm/yyyy" End Sub 

我相信问题在这里:

 d = Cells(i, 2).Value ' here you set d as the variable a = CDate(d) ' at this point a is the current variable Cells(i, 3) = FormatDateTime(d, 2) ' and here you use d again. 

我想你需要用FormatDateTimereplaced

CDate()将值转换为date。
FormateDateTime()需要一个date值才能起作用。 d不是date值。

问题是标准格式是"mm/dd/yyyy"而不是"dd/mm/yyyy" 。 当您尝试将"dd/mm/yyyy"转换为标准date值时,您必须交换date和月份。

这个函数只能处理date值。

 Function FixDDMMYYYY(DateString As String) As Date Dim arDateParts() As String If InStr(DateString, ".") Then arDateParts = Split(DateString, ".") ElseIf InStr(DateString, "-") Then arDateParts = Split(DateString, "-") End If On Error Resume Next FixDDMMYYYY = DateSerial(arDateParts(2), arDateParts(1), arDateParts(0)) On Error GoTo 0 End Function