技术控小李
1/8/2025
嘿,大家好!👋
最近在折腾一个 Access 数据库的 Visual Basic 代码,搞得我有点头大。😅 我想要动态获取一个日期,就是每年都能自动更新到两年前的第一天。原本代码里是硬编码的 #1/1/2020#
,我想改成类似 #1/1/2023#
这样的动态日期。
我试过用 DateAdd
函数来计算,但总是搞不定。代码看起来是这样的:
Private Sub txt_bene_birth_date_BeforeUpdate(Cancel As Integer) Dim s As String Dim twoYearsAgo As Date twoYearsAgo = DateSerial(Year(Date) - 2, 1, 1) ' 计算两年前的第一天 If IsNull(txt_bene_birth_date) Then s = "The beneficiary birthdate field is a required field and can not be left blank." & vbCrLf & vbCrLf & vbCrLf InputError txt_bene_birth_date, s, "Beneficiary Birthdate" Exit Sub End If If Not IsNull(txt_bene_birth_date) And (txt_bene_birth_date < #1/1/1900# Or txt_bene_birth_date > twoYearsAgo) Then s = "The calculator does not support beneficiary birthdates prior to 1/1/1900 or subsequent to " & Format(twoYearsAgo, "m/d/yyyy") & ". " & vbCrLf & vbCrLf & vbCrLf InputError txt_bene_birth_date, s, "Beneficiary Birthdate" Exit Sub End If End Sub
我觉得应该是 DateSerial
函数的用法没问题,但总是有些小错误冒出来。有没有大佬能帮我看看哪里出问题了?🙏
PS: 这个项目有点紧急,老板催得紧,真心希望能尽快搞定!谢谢大家!💼
希望这段代码和描述能帮到你们理解我的问题,期待你们的建议!
全栈小王
1/8/2025
嘿,你好啊!👋
我太理解你遇到的这个问题了,尤其是在紧急项目中,时间总是显得特别紧迫。我之前也在处理日期计算时遇到过类似的麻烦。别担心,我们一起来解决这个问题吧!
从你的代码来看,DateSerial
函数的用法是正确的,用来计算两年前的第一天。你可能遇到的问题是其他地方的逻辑或数据类型不匹配。让我给你一个稍微调整过的版本,并加上一些注释,帮助你更好地理解:
Private Sub txt_bene_birth_date_BeforeUpdate(Cancel As Integer) Dim s As String Dim twoYearsAgo As Date ' 计算两年前的第一天 twoYearsAgo = DateSerial(Year(Date) - 2, 1, 1) ' 检查出生日期是否为空 If IsNull(txt_bene_birth_date) Then s = "The beneficiary birthdate field is a required field and cannot be left blank." & vbCrLf & vbCrLf & vbCrLf InputError txt_bene_birth_date, s, "Beneficiary Birthdate" Exit Sub End If ' 检查出生日期是否在有效范围内 If Not IsNull(txt_bene_birth_date) And (txt_bene_birth_date < #1/1/1900# Or txt_bene_birth_date > twoYearsAgo) Then s = "The calculator does not support beneficiary birthdates prior to 1/1/1900 or subsequent to " & Format(twoYearsAgo, "m/d/yyyy") & ". " & vbCrLf & vbCrLf & vbCrLf InputError txt_bene_birth_date, s, "Beneficiary Birthdate" Exit Sub End If End Sub
txt_bene_birth_date
的数据类型是 Date
,否则可能会导致比较时出错。MsgBox
打印出 twoYearsAgo
的值,确保它是你期望的日期。希望这些建议能帮到你!如果还有其他问题,随时问我哦!加油,你一定能搞定的!💪
如果你需要进一步的帮助,别犹豫,随时联系我!😊