Excel日期格式与VBA中的不同

excel date format not same as in vba

我发现Excel中的日期格式存在问题,显示格式与vba中的numberformat不同
我为此情况创建了一个测试。

Regional Setting for Short Date: MM/dd/yyyy

模块:

1
2
3
4
5
6
7
8
9
10
11
12
13
Function RetrieveNumberFormat() As String
    Dim rng As Range
    Set rng = Application.Caller    
    RetrieveNumberFormat = rng.NumberFormat      
    Set rng = Nothing
End Function

Function SetDate() As String
    Dim rng As Range    
    Set rng = Application.Caller    
    SetDate = Format(Now, rng.NumberFormat)    
    Set rng = Nothing
End Function

在Excel中

1
2
3
4
Col A (Date w default format) | Col B (MM/dd/yyyy)      | Col C (dd-mmm-yyyy)     | Col D (dd/mm/yyyy)      | Col E ([$-404]mm/dd/yyyy)
=Now()                        | =Now()                  | =Now()                  | =Now()                  | =Now()
=RetrieveNumberFormat()       | =RetrieveNumberFormat() | =RetrieveNumberFormat() | =RetrieveNumberFormat() | =RetrieveNumberFormat()
=SetDate()                    | =SetDate()              | =SetDate()              | =SetDate()              | =SetDate()

默认格式(日期A)的日期:

Date

Result

我可以知道为什么Excel将System Date Format MM/dd/yyyy更改为m/d/yyyy,并且有解决方法吗?


尝试改用Application.Text

所以您的SetDate函数看起来像

1
2
3
4
5
6
Function SetDate() As String
    Dim rng As Range    
    Set rng = Application.Caller    
    SetDate = Application.Text(Now, rng.NumberFormat)    
    Set rng = Nothing
End Function

我对Format函数的经验是,它并不那么完整。


我不确定是否足以解决我的问题,但是请随时发表评论或对此进行补充。

我遇到的问题似乎是excel将date formats that begin with (*)保存为m/d/yyyy,这是美国语言环境的默认格式(好吧,Excel是由美国公司创建的),而不是实际的日期格式。

当我们直接在excel中输入值时,它工作正常,excel会自动更改日期格式,但是,当我使用VBA进行输出时,这可能会产生问题,尤其是在使用autofilter时。

我具有增强的SetDate功能:

1
2
3
4
5
6
7
Function SetDate(refCell As Range) As String
    If refCell.NumberFormat ="m/d/yyyy" And refCell.Text = Format(refCell.Value,"Short Date") Then
        SetDate = Format(Now,"Short Date")
    Else
        SetDate = Format(Now, refCell.NumberFormat)
    End If
End Function

但是,当使用日期格式:dd-MMM-yyyy时,此方法仍然存在问题,excel将显示为dd-MM-yyyy

dd-MMM-yyyy


功能设置可能会出现问题。修改它们,这是我的结果。

配方设置:

Formula

结果:

Result

修改后的功能:

1
2
3
4
5
6
7
8
9
Function RetrieveNumberFormat(rng As Range) As String
    Application.Volatile
    RetrieveNumberFormat = rng.NumberFormat
End Function

Function SetDate(rng As Range) As String
    Application.Volatile
    SetDate = Format(Now, rng.NumberFormat)
End Function

请查看这是否对您有利。