【发布时间】:2010-05-25 20:03:40
【问题描述】:
摘要: 每次用户从下拉菜单中选择 3 个选项之一时,我都使用 VB 重新创建查询,如果他们从组合框中选择了任何内容,则会附加 WHERE 子句。然后,我试图让表单上显示的信息刷新,从而根据用户输入过滤表中显示的内容。
1) 使用 VB 动态创建查询。
Private Sub BuildQuery()
' This sub routine will redefine the subQryAllJobsQuery based on input from
' the user on the Management tab.
Dim strQryName As String
Dim strSql As String ' Main SQL SELECT statement
Dim strWhere As String ' Optional WHERE clause
Dim qryDef As DAO.QueryDef
Dim dbs As DAO.Database
strQryName = "qryAllOpenJobs"
strSql = "SELECT * FROM tblOpenJobs"
Set dbs = CurrentDb
' In case the query already exists we should deleted it
' so that we can rebuild it. The ObjectExists() function
' calls a public function in GlobalVariables module.
If ObjectExists("Query", strQryName) Then
DoCmd.DeleteObject acQuery, strQryName
End If
' Check to see if anything was selected from the Shift
' Drop down menu. If so, begin the where clause.
If Not IsNull(Me.cboShift.Value) Then
strWhere = "WHERE tblOpenJobs.[Shift] = '" & Me.cboShift.Value & "'"
End If
' Check to see if anything was selected from the Department
' drop down menu. If so, append or begin the where clause.
If Not IsNull(Me.cboDepartment.Value) Then
If IsNull(strWhere) Then
strWhere = strWhere & " AND tblOpenJobs.[Department] = '" & Me.cboDepartment.Value & "'"
Else
strWhere = "WHERE tblOpenJobs.[Department] = '" & Me.cboDepartment.Value & "'"
End If
End If
' Check to see if anything was selected from the Date
' field. If so, append or begin the Where clause.
If Not IsNull(Me.txtDate.Value) Then
If Not IsNull(strWhere) Then
strWhere = strWhere & " AND tblOpenJobs.[Date] = '" & Me.txtDate.Value & "'"
Else
strWhere = "WHERE tblOpenJobs.[Date] = '" & Me.txtDate.Value & "'"
End If
End If
' Concatenate the Select and the Where clause together
' unless all three parameters are null, in which case return
' just the plain select statement.
If IsNull(Me.cboShift.Value) And IsNull(Me.cboDepartment.Value) And IsNull(Me.txtDate.Value) Then
Set qryDef = dbs.CreateQueryDef(strQryName, strSql)
Else
strSql = strSql & " " & strWhere
Set qryDef = dbs.CreateQueryDef(strQryName, strSql)
End If
结束子
2) 用户从组合框中选择项目的主窗体。
主窗体和子窗体的图片 http://i48.tinypic.com/25pjw2a.png
3) 指向在步骤 1 中创建的查询的子表单。
事件链: 1) 用户从主窗体的下拉列表中选择项目。 2)删除旧查询,生成新查询(同名)。 3) 指向查询的子表单不会更新,但如果您自己打开查询,则会显示正确的结果。
查询名称:qryAllOpenJobs 子窗体的名称:subQryAllOpenJobs 此外, subQryAllOpenJobs = qryAllOpenJobs 的行源 主窗体名称:frmManagement
【问题讨论】:
-
您在更改保存的QueryDef 后是否重新查询了子表单?编辑 QueryDefs 通常不是一个好主意(除非你必须这样做),而且在我看来你应该能够直接设置子表单 Recordsource (自动重新查询)。
-
我试图在子窗体上使用 .requery 过程,但它没有更新,我认为你是对的......这是因为我搞砸了 QueryDef。我一直在寻找记录源操作如何工作的示例,因为这听起来像是我需要的……但我还没有在网上找到任何可靠的示例来帮助我理解它。
-
您是否尝试过将表单的记录源设置为新的 SQL 字符串?根本不需要处理表单的 .Recordset 属性(在 Access 中可用的 10 年里,我从未这样做过)。
-
是的,我现在想通了,我知道 SQL 我只是不太了解 Access(这与大多数人学习的方式有点倒退)。我通过更集中地研究 RecordSource 属性及其出色的工作解决了我的问题。
标签: sql ms-access ms-access-2007 vba