我正在制作一个搜索查询,用于名为' ClassProfile'的表单中。表单是连续的表单,因此以数据表格式列出记录。我在表单上有两个文本框:
用户将使用这两个文本框根据其中包含的值执行各种搜索。它们旁边是一个标有'搜索'的命令按钮。搜索按钮的onClick()事件包含以下用于执行搜索的代码:
Private Sub cmdSearch_Click()
Dim strsearching As String
Dim strm As String
Dim tname As String
strm = Me.clsBox.Value
tname = Me.NameBox.Value
If Not IsNull(strm) Then
If IsNull(strsearching) Then
strsearching = "(([ClassProfile].[Class]) LIKE ""*" & strm & "*"")"
End If
Else: strsearching = ""
End If
If Not IsNull(tname) Then
If Not IsNull(strsearching) Then
strsearching = strsearching & " AND (([ClassProfile].[Class Teacher]) LIKE ""*" & tname & "*"")"
Else: strsearching = "(([ClassProfile].[Class Teacher]) LIKE ""*" & tname & "*"")"
End If
Else: strsearching = ""
End If
Dim sql As String
If Not IsNull(strsearching) Then
sql = "SELECT * FROM [ClassProfile] WHERE " & strsearching
Else: sql = "ClassProfile"
End If
Me.RecordSource = sql
End Sub
执行搜索时,表单的记录集没有任何反应,代码无法正常工作。任何帮助表示赞赏。
答案 0 :(得分:1)
更新:更改了ISNULL(strsearching)检查。这是有效的。我改变了你的Null检查以避免处理有时空值。
Option Compare Database
Option Explicit
Private Sub cmdSearch_Click()
Dim strsearching As String
Dim strm As String
Dim tname As String
Dim sql As String
strm = Nz(Me.clsBox.Value)
tname = Nz(Me.NameBox.Value)
strsearching = ""
If strm <> "" Then
strsearching = "(([ClassProfile].[Class]) LIKE ""*" & strm & "*"")"
End If
If tname <> "" Then
If strsearching <> "" Then
strsearching = strsearching & " AND (([ClassProfile].[Class Teacher]) LIKE ""*" & tname & "*"")"
Else
strsearching = "(([ClassProfile].[Class Teacher]) LIKE ""*" & tname & "*"")"
End If
End If
If strsearching <> "" Then
sql = "SELECT * FROM [ClassProfile] WHERE " & strsearching
Else
sql = "ClassProfile"
End If
Debug.Print sql
Me.RecordSource = sql
End Sub
答案 1 :(得分:0)
像魅力韦恩一样工作。所有的赞美。修改它只是为了准确,这是最终的代码:
strm = Me.clsBox.Value
tname = Me.NameBox.Value
strsearching = ""
If Len(Trim(Me.clsBox.Value)) <> 0 Then
strsearching = "(([ClassProfile].[Class]) LIKE ""*" & strm & "*"")"
End If
If Len(Trim(Me.NameBox.Value)) <> 0 Then
If strsearching <> "" Then
strsearching = strsearching & " AND (([ClassProfile].[Class Teacher]) LIKE ""*" & tname & "*"")"
Else: strsearching = "(([ClassProfile].[Class Teacher]) LIKE ""*" & tname & "*"")"
End If
End If
Dim sql As String
If strsearching <> "" Then
sql = "SELECT * FROM [ClassProfile] WHERE " & strsearching
Else: sql = "ClassProfile"
End If
Me.RecordSource = sql