excel的date格式与vba不一样
我在excel中发现了一个date格式的问题,显示格式不像vba中的numberformat
那样相同,我为这种情况创build了一个testing。
Regional Setting for Short Date: MM/dd/yyyy
模块:
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中
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()
具有默认格式的date(Col A):
结果:
我可以知道为什么Excel将System Date Format MM/dd/yyyy
更改为m/d/yyyy
,并且有办法解决吗?
尝试使用Application.Text
来代替。
所以你的SetDate函数看起来像
Function SetDate() As String Dim rng As Range Set rng = Application.Caller SetDate = Application.Text(Now, rng.NumberFormat) Set rng = Nothing End Function
Format
函数的经验是它不完整。
如何设置你的function可能是一个问题。 修改它们,这里是我的结果。
配方设置:
结果:
修改的function:
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
请看看这是否有效。
我不确定是否足够解决我的问题,但可以随意评论或加强这一点。
我遇到的问题似乎是,excel将保存date formats that begin with (*)
为m/d/yyyy
(美国区域设置的默认格式(呃,Excel由美国公司创build)),而不是实际的date格式。
当我们直接在Excel中input值时,它工作的很好,Excel会自动更改date格式,但是当我使用VBA输出时,这可能会产生一个问题,特别是在使用autofilter
。
我已经增强了SetDate
function:
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
但是,在使用date格式时,这种方法仍然存在问题: dd-MMM-yyyy
,其中excel将显示为dd-MM-yyyy
。