簡體   English   中英

將日期范圍添加到表單以優化搜索的 VBA 代碼

[英]VBA code to add a date range to a form to refine search

我已經有一個帶有“類型”組合下拉列表的表單(這是我正在搜索的抗體字段記錄)。 “SearchRecords”按鈕啟動代碼。 我想在表單中添加開始和結束日期以優化搜索。 我為StartDateEndDate創建了日期文本框。 我當前的代碼如下。 我需要有關 VB 代碼的幫助以獲取日期范圍。

Private Sub SearchRecords_Click()
    Dim strSQL As String
    On Error Resume Next
    Combo24.SetFocus
    DoCmd.Hourglass True
    strSQL = "SELECT * FROM tblAGV_Log WHERE [Type] = '" & Me.Combo24.Text & "' Order by Date DESC"
    Me.RecordSource = ""
    Me.RecordSource = strSQL
    DoCmd.Hourglass False
End Sub

展示比描述更容易,但我會像這樣擴展你的日常工作:

Private Sub SearchRecords_Click()
    Dim strSQL As String
    Dim strWhere As String
    Dim strOp As String

    On Error Resume Next

    DoCmd.Hourglass True
    strSQL = "SELECT * FROM tblAGV_Log"

    strWhere = ""
    strOp = ""
    If Not IsNull(Me.Combo24.Value) Then
        strWhere = strWhere & strOp & "([Type] = '" & Me.Combo24.Value & "')"
        strOp = " And "
    End If
    If Not IsNull(Me.StartDate.Value) Then
        strWhere = strWhere & strOp & "([Date] >= #" & Me.StartDate.Value & "#)"
        strOp = " And "
    End If
    If Not IsNull(Me.EndDate.Value) Then
        strWhere = strWhere & strOp & "([Date] <= #" & Me.EndDate.Value & "#)"
        strOp = " And "
    End If

    If Len(strWhere) > 0 then
        strSQL = strSQL & " WHERE " & strWhere
    End If
    strSQL = strSQL & " Order by [Date] DESC"

    Me.RecordSource = strSQL
    DoCmd.Hourglass False

End Sub

這會讓你非常接近。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM