FindFirst声明中的多个条件

时间:2016-08-28 14:15:57

标签: access-vba

Sub Main()
StartTime = Now()
TDate = CDate(Format(Now(), "MM/DD/YYYY"))
My = Environ("Username")
Set db = CurrentDb
Set rs = db.OpenRecordset("Emp", dbOpenDynaset)
Criteria = "ID = '" & My & "' And From_Date >= '" & TDate & "' And To_Date <= '" & StartTime & "' "
rs.FindFirst Criteria
If rs.NoMatch Then
MsgBox "Record not found"
else
MsgBox "Record found"
end if

请帮助运行此代码,因为我想在开始日期和开头之间找到第一条记录。结束日期。

2 个答案:

答案 0 :(得分:0)

对于约会日期,您应使用“#”作为封闭字符:

Criteria = "ID = '" & My & "' And From_Date >= #" & TDate & "# And To_Date <= #" & StartTime & "# "

答案 1 :(得分:0)

您正在混合日期和时间格式:

Sub Main()

    ' Dim StartTime As Date
    ' Dim TDate As Date

    StartTime = Now
    TDate = DateValue(StartTime)
    My = Environ("Username")

    Set db = CurrentDb
    Set rs = db.OpenRecordset("Emp", dbOpenDynaset)
    Criteria = "ID = '" & My & "' And From_Date >= #" & Format(TDate, "yyyy\/mm\/dd") & "# And To_Date <= #" & Format(StartTime, "yyyy\/mm\/dd") & "#'"
    rs.FindFirst Criteria
    If rs.NoMatch Then
        MsgBox "Record not found"
    Else
        MsgBox "Record found"
    End If

End Sub

但是,它可以简化为:

Sub Main()

    My = Environ("Username")

    Set db = CurrentDb
    Set rs = db.OpenRecordset("Emp", dbOpenDynaset)
    Criteria = "ID = '" & My & "' And From_Date >= Date() And To_Date <= Now()"
    rs.FindFirst Criteria
    If rs.NoMatch Then
        MsgBox "Record not found"
    Else
        MsgBox "Record found"
    End If

End Sub