Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
917 views
in Technique[技术] by (71.8m points)

excel - Difference between DateValue and CDate in VBA

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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)).


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...