且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何将日期字符串转换并比较Excel中的日期

更新时间:2023-01-27 23:01:07

我正在升级以下内容对答案的评论:



除非你有一个非常具体的理由这样做(现在我不能想到任何),日期(和其他值)在细胞中真的不应该像你所显示的字符串那样被硬编码。硬编码这样的字符串使它看不见和僵化。用户将只看到 TRUE FALSE ,不表示这是什么意思。



我只是把它的日期 7/29/2011 12:58:00 PM 自己的A1,并将单元格的格式设置为某种日期格式。然后你可以说 = A1> NOW()



与@ jonsca和@Tiago Cardoso的答案相反,这个答案没有解决你的具体问题,但是再一次,你所问的是对我来说真的很糟糕的做法!


= "7/29/2011 12:58:00 PM" > NOW()

I'd like this expression to return FALSE and yet it returns TRUE.

I know I can break apart my datetime into a date and a time and add them together as follows:

= DateValue("7/29/2011") + TimeValue("12:58:00 PM") > NOW()

But, this seems inelegant to me. I want a simple function or approach that looks nice and I feel certain that it's out there but I just can't find it.

I also know there is a VBA function called CDate which can typecast the string into a datetime and that would be perfect. But, I don't see how to call a VBA function in an excel cell.

I'm upgrading the following from a comment to an answer:

Unless you have a very specific reason to do so (and right now I can't think of any), dates (and other values) really shouldn't be "hard-coded" in cells as strings like you show. Hard-coding the string like that makes it invisible and inflexible. The user will just see TRUE or FALSE with no indication of what this means.

I would just put your date 7/29/2011 12:58:00 PM in a cell on its own e.g. A1, and set the cell's format to some date format. Then you can say = A1 > NOW().

Contrary to @jonsca's and @Tiago Cardoso's answers, this answer doesn't address your specific question, but then again, what you are asking seems like really bad practice to me!