修剪功能导致日期格式更改 [英] Trim function causes date format change

查看:153
本文介绍了修剪功能导致日期格式更改的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

首先,重要的是要注意,我在英国,所以标准日期格式是dd / mm / yyyy



在A1中,我有一个日期:02 / 05/2017(dd / mm / yyyy)



我可以在即时窗口中确认:

 ?CLng(Range(A1)。Value)
42857

现在,如果我执行以下操作:

 范围(A1)Value = Range ).Value 

你可以猜到,没有发生什么 - 日期还是02/05/2017而数值仍然是42857



但是如果我使用修剪:

  Range(A1)Value = Trim(Range(A1)。Value)

日期更改为05/02/2017。这不只是格式化 - 数值也变为42771。






这是什么关于 Trim()方法导致以美国格式读取日期,然后用新的日期值转换回英国格式?这是一个错误?

解决方案

从评论中的讨论中:



VBA中的默认或令牌格式(不是Excel本身,如Macro Man正确指出)是美国英语 - 不管区域设置或单元格格式。



当您在一个日期执行VBA文本功能,这些功能的输出是文本格式。所以 Trim(Range(A1)。Value)的结果是一个字符串。这个字符串类似于一个正确的美国日期,所以当你把它插入一个单元格时,Excel会把它识别为一个美国的日期。



所以这两个隐含的转换都会发生。当您读取单元格内容并将其传递到 trim():date->文本转换时,首先发生;当您将其写回到Excel单元格时,第二次发生:text->日期转换。第二个转换没有关于格式的信息,所以它假定是美国英语。



(您应该可以使用任何文本功能实现相同的结果,而不仅仅是 trim()。)


Firstly, important to note that I'm in the UK so standard date format is dd/mm/yyyy

In a A1, I have a date: 02/05/2017 (dd/mm/yyyy)

I can confirm this in the immediate window:

?CLng(Range("A1").Value)
42857

Now, if I do the following:

Range("A1").Value = Range("A1").Value

you can probably guess, nothing happens - the date is still 02/05/2017 and the numeric value is still 42857

But if I use trim with it:

Range("A1").Value = Trim(Range("A1").Value)

The date is changed to 05/02/2017. This isn't just formatting - the numeric value has also changed to 42771.


What is it about the Trim() method that causes the date to be read in US format and then converted back to UK format with a new date value? Is this a bug?

解决方案

From the discussion in comments:

The default or "token" format in VBA (not Excel itself, as Macro Man rightly pointed out) is US English - regardless of regional settings or cell formatting.

When you do VBA text functions on a date, the output of those functions are in text format. So the result of Trim(Range("A1").Value) is a string. This string happens to resemble a proper US date, so when you insert it into a cell, Excel recognizes it as a US date.

So two implicit conversions happen. The first happens when you read the cell contents and pass it to trim(): date->text conversion; the second happens when you write it back to an Excel cell: text->date conversion. The second conversion has no information about the format, so it assumes US English.

(You should be able to achieve the same result with any text function, not just trim().)

这篇关于修剪功能导致日期格式更改的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆