将日期格式dd / mm / yyyy更改为mm / dd / yyyy

时间:2020-05-25 21:59:51

标签: vba date

数据源是使用dd/mm/yyyy格式的txt文件。日期填充在两列中:N和O。所需的输出是将这两列中的所有日期都重新格式化为mm/dd/yyyy

txt文件:

N           O
05/12/20    14/05/2020

到目前为止,我有以下代码:

Sub Format_Dates()
Range("N:N").Select
    Selection.NumberFormat = "mm/dd/yy;@"

Range("O:O").Select
    Selection.NumberFormat = "mm/dd/yy;@"
End Sub

该代码在13到31天之间无效。

赞赏任何输入。 THX

2 个答案:

答案 0 :(得分:0)

为什么只放两个y?应该是“ mm / dd / yyyy”:

Range("N:O").NumberFormat = "mm/dd/yyyy"

答案 1 :(得分:0)

首先考虑系统的区域设置。因为如果您得到11/10/2001可能会一团糟,那么什么日期合适? Thursday, October 11, 2001还是Saturday, November 10, 2001?那取决于你。

继续此免责声明:

Sub formatDate()
    'dd/mm/yyyy
    'to
    'mm/dd/yyyy

    Dim str As String 'your string with the date this way: dd/mm/yyyy
    Dim D 'to days
    Dim M 'to months
    Dim Y 'to years

    str = "11/10/2001" 'dd/mm/yyyy
    D = CInt(Left(str, 2)) 'Need to cast this "11" to this 11.
    M = CInt(Mid(str, 4, 2))
    Y = CInt(Right(str, 4))

    Dim DD As Date 'define the vas as a Date to tell the system to use the regional setting of dates
    DD = DateSerial(Y, M, D) 'Now we just need to insert the values inside DateSerial as the function need
    Range("N1").Value = DD 'Send the value to the cell you need, here I use N1

    'Range("N:N").NumberFormat = "[$-F800]dddd, mmmm dd, yyyy" 'Use the format you want. I like this.

    Range("N:O").NumberFormat = "mm/dd/yyyy" 'This is your format. Both columns 
End Sub