如何创建高级搜索表单

时间:2013-10-20 10:09:36

标签: ms-access

我有这个代码使用MS Access创建多字段搜索表单,并且它引用了syntex错误;

Private Sub cmdSearch_Click()
On Error GoTo errr
Me.infot_subform1.Form.RecordSource = " select * from infot " & BuildFilter
Me.infot_subform1.Requery
Exit Sub
errr:
MsgBox Err.Description

End Sub
Private Function BuildFilter() As Variant
Dim varWhere As Variant
Dim tmp As String
tmp = """"
Const conJetDate = "\#dd\/mm\/yyyy\#"
varWhere = Null
If Me.txtID > "" Then
varWhere = varWhere & "[ID] like" & Me.txtID & "AND"
End If
If Me.txtName > "" Then
varWhere = varWhere & "[Name] like" & tmp & Me.txtName & tmp & "AND"
End If
If IsNull(varWhere) Then
varWhere = ""
Else
varWhere = "Where" & varWhere
If Right(varWhere, 5) = "AND" Then
varWhere = Left(varWhere, Len(varWhere) - 5)
End If
End If
BuildFilter = varWhere
End Function

1 个答案:

答案 0 :(得分:1)

假设这是一个运行时而不是编译时错误(否则,你会说什么行报告有问题,对吧?),你没有在关键字周围包含必要的空格。例如,

"[ID] like" & Me.txtID & "AND"

最终将会出现类似

的内容
[ID] like123456AND

那就是说,我会重写BuildFilter看起来像这样:

Private Function BuildFilter() As String
  Dim WhereClause As String
  If Not IsNull(Me.txtID.Value) Then
    WhereClause = "[ID] = " & Me.txtID.Value
  End If
  If Not IsNull(txtName.Value) Then
    If Len(WhereClause) <> 0 Then WhereClause = WhereClause + " AND "
    Dim S As String
    S = Me.txtName.Value
    ' add wildcards if none explicitly specified
    If (Len(S) > 2) And (Left$(S, 1) <> "*") And (Right$(S, 1) <> "*") Then
        S = "*" + S + "*"
    End If
    ' Access SQL allows single as well as double quotes for string literals
    WhereClause = WhereClause + "[Name] LIKE '" + Replace(S, "'", "''") + "'"
  End If
  If Len(WhereClause) <> 0 Then
    BuildFilter = "WHERE " + WhereClause
  Else
    BuildFilter = ""
  End If
End Function
  1. 我已假设LIKE txtID假设ID为数字,因为您没有将其包装在原始代码中的引号字符中。
  2. 相反,我添加了txtName的星号,因为使用LIKE毫无意义。
  3. 您对变体的使用似乎有点混乱,所以我已将其删除。
  4. 我已明确访问文本框'Value属性,但这只是个人偏好。
  5. 无论是显式访问还是隐式访问,Value如果字段为空,则返回将为Null(不是空字符串)的变体。无论如何,使用MyVar > ""测试空字符串是很奇怪的,即使形式正确(通常使用MyVar <> ""Len(MyVar) <> 0)。