【问题标题】:Search button using more than one text field Access vba使用多个文本字段的搜索按钮访问 vba
【发布时间】:2022-01-07 04:59:21
【问题描述】:

这是我下面的代码。我正在尝试使用两个不同的日期、公司名称来搜索数据库

当日期字段之一为空或 null 时,我收到错误消息。如果日期搜索字段为空,如何解决此问题或绕过以在搜索中忽略它或搜索空字段?

Dim SQL As String
SQL = "SELECT * from qryRequestInternal where ([DateRequestSent] = #" & txt_Search_Sdate & "# AND [DateReceived] = #" & txt_Search_Rdate & "# AND (companyName like ""*" & txt_SCompNa & "*"") )"
Me.sfrmRequestInternal.Form.RecordSource = SQL
Me.sfrmRequestInternal.Form.Requery

Me.sfrmRequestInternal_col.Form.RecordSource = SQL
Me.sfrmRequestInternal_col.Form.Requery
End Sub


【问题讨论】:

  • NZ 将帮助我思考访问权限,或检查之前的值并从不同的组合构建 where 子句。

标签: sql vba forms ms-access search


【解决方案1】:

您将需要检查 Null 值并根据具有值(即非空)的控件构建 SQL 字符串。

下面的示例使用辅助函数来构建 sql 字符串。如果没有插入任何内容,它只会运行Select * from qryRequestInternal 而没有任何条件。

Private Function SqlWhere() As String

    Dim retvalue As String
    
    'sent date
    With txt_Search_Sdate
        If Not IsNull(.Value) Then
            retvalue = " WHERE [DateRequestSent] = #" & Format(.Value, "mm/dd/yyyy") & "#"
        End If
    End With
    
    'received date
    With txt_Search_Rdate
        If Not IsNull(.Value) Then
            retvalue = IIf(Len(retvalue) = 0, " WHERE", retvalue & " AND") & " [DateReceived] = #" & Format(.Value, "mm/dd/yyyy") & "#"
        End If
    End With
    
    'company
    With txt_SCompNa
        If Not IsNull(.Value) Then
            retvalue = IIf(Len(retvalue) = 0, " WHERE", retvalue & " AND") & " [companyName] Like '*" & .Value & "*'"
        End If
    End With
    
    SqlWhere = retvalue
    
End Function

称呼它:

Dim sqlString As String
    sqlString = "SELECT * from qryRequestInternal" & SqlWhere()

Debug.Print sqlString

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-12-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-02-19
    • 2017-08-10
    相关资源
    最近更新 更多