我想使用VBA代码在我的数据库的开头弹出一条警告信息,并告诉我他们的年龄超过50岁的人的名字只是我可以达到的最后一次
For i = 1 To 4
If [Forms]![1]![years] >=50 Then
MsgBox "employees:" & Me.name
End If
Next i
答案 0 :(得分:1)
您可以使用我的简单功能:
Public Function AgeSimple( _
ByVal datDateOfBirth As Date) _
As Integer
' Returns the difference in full years from datDateOfBirth to current date.
'
' Calculates correctly for:
' leap years
' dates of 29. February
' date/time values with embedded time values
'
' DateAdd() is used for check for month end of February as it correctly
' returns Feb. 28. when adding a count of years to dates of Feb. 29.
' when the resulting year is a common year.
' After an idea of Markus G. Fischer.
'
' 2007-06-26. Cactus Data ApS, CPH.
Dim datToday As Date
Dim intAge As Integer
Dim intYears As Integer
datToday = Date
' Find difference in calendar years.
intYears = DateDiff("yyyy", datDateOfBirth, datToday)
If intYears > 0 Then
' Decrease by 1 if current date is earlier than birthday of current year
' using DateDiff to ignore a time portion of datDateOfBirth.
intAge = intYears - Abs(DateDiff("d", datToday, DateAdd("yyyy", intYears, datDateOfBirth)) > 0)
End If
AgeSimple = intAge
End Function
表单上按钮的click事件中的循环(示例):
Dim rs As DAO.Recordset
Set rs = Me.RecordsetClone
If rs.RecordCount > 0 Then
rs.MoveFirst
End If
While Not rs.EOF
If AgeSimple(Nz(rs!DOB.Value, Date)) >= 50 Then
MsgBox "Employee: " & rs![Name].Value, vbInformation + vbOKOnly, "50+"
End If
rs.MoveNext
Wend
Set rs = Nothing
当然,请将此处的字段/控件名称替换为您的实际表单。
修改强>
演示是here