本文介绍了VBA中的DateValue和CDate之间的区别的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是VBA的新人,我正在研究一个模块,从电子表格中读取数据,并根据电子表格中的日期计算值。我以变量的形式读取字符串,然后我正在使用CDate将值更改为Date。然而,我刚刚遇到了DateValue,我想知道两个函数之间有什么区别,哪一个是更好的使用。

解决方案

DateValue 将只返回日期。 CDate 将保留日期和时间:

 ? DateValue(2014-07-24 15:43:06)
24/07/2014

? CDate(2014-07-24 15:43:06)
24/07/2014 15:43:06

同样,您可以使用 TimeValue 仅返回时间部分:

 ? TimeValue(2014-07-24 15:43:06)
15:43:06

? X-454545454545 X- 20045 X- 20045 X- 20045 X- 20045 X- 20045 X- 20045 X- 20045 X- 20045 X- TimeSerial(12,0,0)
True

另外,如guitarthrower所说, DateValue (和 TimeValue )将只接受 String 参数,而 CDate 也可以处理数字。要模拟这些数字类型的函数,请使用 CDate(Int(num)) CDate(num - Int(num))


I am new to VBA and I am working on a module to read in data from a spreadsheet and calculate values based on dates from the spreadsheet. I read in the variables as a String and then am currently changing the values to a Date using CDate. However I just ran across DateValue and I was wondering what the difference between the two functions were and which one is the better one to use.

解决方案

DateValue will return only the date. CDate will preserve the date and time:

? DateValue("2014-07-24 15:43:06")
24/07/2014

? CDate("2014-07-24 15:43:06")
24/07/2014 15:43:06 

Similarly you can use TimeValue to return only the time portion:

? TimeValue("2014-07-24 15:43:06")
15:43:06 

? TimeValue("2014-07-24 15:43:06") > TimeSerial(12, 0, 0)
True

Also, as guitarthrower says, DateValue (and TimeValue) will only accept String parameters, while CDate can handle numbers as well. To emulate these functions for numeric types, use CDate(Int(num)) and CDate(num - Int(num)).

这篇关于VBA中的DateValue和CDate之间的区别的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-25 04:13