excel date format not same as in vba
我发现Excel中的日期格式存在问题,显示格式与vba中的
我为此情况创建了一个测试。
模块:
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)的日期:
结果:
我可以知道为什么Excel将
尝试改用
所以您的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 |
我对
我不确定是否足以解决我的问题,但是请随时发表评论或对此进行补充。
我遇到的问题似乎是excel将
当我们直接在excel中输入值时,它工作正常,excel会自动更改日期格式,但是,当我使用VBA进行输出时,这可能会产生问题,尤其是在使用
我具有增强的
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 |
但是,当使用日期格式:
功能设置可能会出现问题。修改它们,这是我的结果。
配方设置:
结果:
修改后的功能:
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 |
请查看这是否对您有利。