0

我有这段代码可以使用 MS Access 创建多字段搜索表单,并引用语法错误;

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
4

1 回答 1

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. 我在假设是数字的情况下删除了LIKEfor ,因为您没有在原始代码中将它包含在引号字符中。txtIDID
  2. 相反,我已经添加了星号,txtName因为否则使用LIKE是毫无意义的。
  3. 您对变体的使用似乎有些混乱,因此我将其删除。
  4. 我已经Value明确地访问了文本框的属性,但这只是个人喜好。
  5. 无论是显式访问还是隐式访问,如果字段为空,Value则返回一个变体Null(不是空字符串)。无论如何测试空字符串MyVar > ""还是很奇怪的,即使形式上是正确的(通常你使用MyVar <> ""or Len(MyVar) <> 0)。
于 2013-10-20T10:47:55.447 回答