vba VBA中DateValue和CDate的区别

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/24944662/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-08 18:28:36  来源:igfitidea点击:

Difference between DateValue and CDate in VBA

vbaexcel-vbaexcel

提问by Ryan Newman

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.

我是 VBA 的新手,我正在开发一个模块,用于从电子表格中读取数据并根据电子表格中的日期计算值。我将变量作为字符串读入,然后当前正在使用 CDate 将值更改为日期。然而,我刚刚遇到了 DateValue,我想知道这两个函数之间的区别是什么,哪个更好用。

回答by Chel

DateValuewill return only the date. CDatewill preserve the date and time:

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 

Similarly you can use TimeValueto return only the time portion:

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

? 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 Stringparameters, while CDatecan handle numbers as well. To emulate these functions for numeric types, use CDate(Int(num))and CDate(num - Int(num)).

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

回答by guitarthrower

CDatewill convert a number or text to a date.

CDate将数字或文本转换为日期。

CDate(41035) 'Converts to a date of 5/6/2012
CDate("1/15/2014") 'Converts to a date of 1/15/2014

DateValuewill convert date in text format (only) to a date.

DateValue将文本格式的日期(仅)转换为日期。

DateValue("1/15/2014") 'Converts to a date of 1/15/2014
DateValue(41035) 'Throws a mismatch error

回答by Alex

Both CDate and DateValue, when used in vba, converts a value to a Date (dd/mm/yyyy format):
1)
LstrDate = "July 24, 2014"
LDate = CDate(LstrDate)

CDate 和 DateValue 在 vba 中使用时,都将值转换为日期(dd/mm/yyyy 格式):
1)
LstrDate = "July 24, 2014"
LDate = CDate(LstrDate)

2)
LDate = DateValue("July 24, 2014")

2)
LDate = DateValue("July 24, 2014")

Both return the same result.

两者都返回相同的结果。

However DateValue returns the serial number of a date if used in application level (spreadsheet)

但是,如果在应用程序级别(电子表格)中使用,则 DateValue 返回日期的序列号