สร้าง Module ใส่โค๊ดดังนี้
Public Function CalAge(FieldDateOfBirth) As String
Dim DayOfBirth As String
Dim MonthOfBirth As String
Dim YearOfBirth As String
If IsNull(FieldDateOfBirth) Then
CalAge = ""
Else
DayOfBirth = IIf(DateDiff("d", DateAdd("m", DateDiff("m", [FieldDateOfBirth], Date), [FieldDateOfBirth]), Date) < 0, DateDiff("d", DateAdd("m", DateDiff("m", [FieldDateOfBirth], Date) - 1, [FieldDateOfBirth]), Date), DateDiff("d", DateAdd("m", DateDiff("m", [FieldDateOfBirth], Date), [FieldDateOfBirth]), Date))
MonthOfBirth = IIf(DateDiff("d", DateAdd("m", DateDiff("m", [FieldDateOfBirth], Date), [FieldDateOfBirth]), Date) < 0, (DateDiff("m", [FieldDateOfBirth], Date) - 1) Mod 12, DateDiff("m", [FieldDateOfBirth], Date) Mod 12)
YearOfBirth = IIf(DateDiff("d", DateAdd("m", DateDiff("m", [FieldDateOfBirth], Date), [FieldDateOfBirth]), Date) < 0, (DateDiff("m", [FieldDateOfBirth], Date) - 1) \ 12, DateDiff("m", [FieldDateOfBirth], Date) \ 12)
CalAge = IIf(Left(DayOfBirth, 1) = 0, "", DayOfBirth & "ปี ") & IIf(Left(MonthOfBirth, 1) = 0, "", MonthOfBirth & "เดือน ") & IIf(Left(DayOfBirth, 1) = 0, "", DayOfBirth & "วัน")
End If
End Function
Public Function CalDay(FieldDateOfBirth) As String
Dim DayOfBirth As String
If IsNull(FieldDateOfBirth) Then
CalDay = ""
Else
DayOfBirth = IIf(DateDiff("d", DateAdd("m", DateDiff("m", [FieldDateOfBirth], Date), [FieldDateOfBirth]), Date) < 0, DateDiff("d", DateAdd("m", DateDiff("m", [FieldDateOfBirth], Date) - 1, [FieldDateOfBirth]), Date), DateDiff("d", DateAdd("m", DateDiff("m", [FieldDateOfBirth], Date), [FieldDateOfBirth]), Date))
CalDay = DayOfBirth & " วัน "
End If
End Function
Public Function CalMonth(FieldDateOfBirth) As String
Dim MonthOfBirth As String
If IsNull(FieldDateOfBirth) Then
CalMonth = ""
Else
MonthOfBirth = IIf(DateDiff("d", DateAdd("m", DateDiff("m", [FieldDateOfBirth], Date), [FieldDateOfBirth]), Date) < 0, (DateDiff("m", [FieldDateOfBirth], Date) - 1) Mod 12, DateDiff("m", [FieldDateOfBirth], Date) Mod 12)
CalMonth = MonthOfBirth & " เดือน "
End If
End Function
Public Function CalYear(FieldDateOfBirth) As String
Dim YearOfBirth As String
If IsNull(FieldDateOfBirth) Then
CalYear = ""
Else
YearOfBirth = IIf(DateDiff("d", DateAdd("m", DateDiff("m", [FieldDateOfBirth], Date), [FieldDateOfBirth]), Date) < 0, (DateDiff("m", [FieldDateOfBirth], Date) - 1) \ 12, DateDiff("m", [FieldDateOfBirth], Date) \ 12)
CalYear = YearOfBirth & " ปี "
End If
End Function
ที่คิวรี่ใส่ SQL
SELECT DOB, CalAge([DOB]) AS Age, CalDay([DOB]) AS [Day], CalYear([DOB]) AS [YEAR], CalMonth([DOB]) AS [Month]
FROM MyTable;
สามารถใช้ชื่อฟังชั่นในการ แสดงผลได้เลยเช่น
ต้องการอายุจากวันเกิดก็ใส่
คำนวนอายุ: CalAge([ชื่อฟิลล์วันเกิด])
ส่วนหาวัน CalDay([ชื่อฟิลล์วันเกิด])
หาเดือน CalMonth([ชื่อฟิลล์วันเกิด])
หาปี CalYear([ชื่อฟิลล์วันเกิด])