通过文本框来计算年龄

时间:2019-10-19 14:00:48

标签: excel vba

“我有一个包含两个文本框的用户窗体,其中TextBox1属于出生日期,textbox2属于年龄。如何在TextBox1中输入出生日期然后在TextBox2中显示完整的年龄和月份时创建代码?”

Dim Age
Dim Birthday As Date
Birthday = CDate(TextBox1.Text)
Age = Year(Date) - Year(Birthday)
TextBox2.Value = Age
我希望输出例如25.10,但实际输出25

1 个答案:

答案 0 :(得分:0)

DateDiff函数以多种格式提供两个日期之间的差异。使用Date Diff函数,我们可以获取日期之间的月份数,并将其转换为如下所示的所需格式

Dim Age
Dim Birthday As Date
Dim years As Integer
Dim months As Integer
Birthday = CDate(TextBox1.Text)
Age = DateDiff("m", (Birthday) , (Date) )
years = Application.WorksheetFunction.RoundDown(Age / 12, 0)
months = Age Mod 12