【问题标题】:calculate age from textbox dob从文本框 dob 计算年龄
【发布时间】:2019-10-19 14:00:48
【问题描述】:

“我的用户表单包含两个文本框 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

【问题讨论】:

  • 你为什么期待 25.10?减去两个整数(年份值)将始终返回一个整数
  • 25.10 表示年龄 25 岁 10 个月。如果有其他代码请解释我
  • 那么在计算年龄时需要考虑月份。

标签: excel vba


【解决方案1】:

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

【讨论】:

  • ``` Private Sub TextDOB_AfterUpdate() Dim Age Dim Birthday As Date Dim years As Integer Dim Month As Integer Birthday = CDate(TextDOB.Text) Age = DateDiff("m", (Date), (生日)) 年 = Application.WorksheetFunction.RoundDown(Age / 12, 0) 月 = 年龄 Mod 12 Textage.Value = 年 & "." & 月 ``` 文本值是负数,如 -25.-10
  • 参数可能必须在 datediff 函数中互换。在@Yogesh 上面更新了我的答案
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2023-03-10
  • 2022-01-24
  • 1970-01-01
  • 2013-01-23
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多