在VBA中使用Datedif函数求时间间隔
2012-10-03 22:10阅读:
A1单元格内容为:2005-9-8,B3单元格内容为:2007-4-5,要求出它们间隔的年、月、日,在工作表中可以使用Datedif函数,而且结果非常精确,但在VBA中却比较麻烦。因为Datedif函数不能直接在VBA中使用,而使用VBA提供的函数却不能得到精确的计算结果。于是很多人在写代码时就自编一个函数来实现Datedif |
函数的功能,其实借助VBA的Evaluate函数我们同样可以很方便地在VBA中使用Datedif函数:
一、求单元格时间间隔:
A1单元格内容为:2005-9-8,B3单元格内容为:2007-4-5:
Sub
test1()
MsgBox
'间隔'
& Application.Evaluate('=Datedif(a1,b3,''y'')') &
'年'
MsgBox
'间隔'
& Application.Evaluate('=Datedif(a1,b3,''m'')') &
'月'
MsgBox
'间隔'
& Application.Evaluate('=Datedif(a1,b3,''d'')') &
'日'
End
Sub
二、求两个TextBox的时间间隔:
TextBox1单元格内容为:2005-9-8,TextBox2单元格内容为:2007-4-5:
Sub test2()
MsgBox '=Datedif(''' &
TextBox1.Text & ''',''' & TextBox2.Text &
''',''y'')'
MsgBox '间隔' &
Application.Evaluate('=Datedif(''' & TextBox1.Text &
''',''' & TextBox2.Text & ''',''y'')') &
'年'
End
Sub
三、求两个变量的时间间隔:
Sub
test3()
Dim time1, time2
time1 = '2005-9-8'
time2 = '2007-4-7'
MsgBox '间隔' &
Application.Evaluate('=Datedif(''' & time1 & ''',''' &
time2 & ''',''y'')') & '年'
End Sub