会员登录 - 用户注册 - 网站地图 Office中国(office-cn.net),专业Office论坛
当前位置:主页 > 技巧 > Access技巧 > 查询视图 > 正文

在Access中利用搜索窗体中的值生成动态查询

时间:2009-08-29 08:40 来源:网络 作者:佚名 阅读:

有时,您可能需要创建一个窗体来用作搜索窗体,以便能够在窗体上输入值并动态生成适当的 SQL 字符串。下列步骤将向您演示如何动态生成使用 BuildCriteria 方法的查询字符串。

Microsoft 提供的编程示例只用于演示目的,不附带任何明示或暗示的保证。这包括但不限于对适销性或特定用途适用性的暗示保证。本文假定您熟悉所演示的编程语言以及用于创建和调试过程的工具。Microsoft 的支持工程师可以帮助解释某个特定过程的功能,但是他们不会修改这些示例以提供额外的功能或构建过程以满足您的特殊需求。警告:执行本示例中的步骤将会修改示例数据库 Northwind.mdb。您可能需要备份 Northwind.mdb 文件,并在该数据库的副本上执行这些步骤。


启动 access。
在“帮助”菜单上,指向“示例数据库”,然后单击“罗斯文示例数据库”。
在“设计”视图中打开“客户”窗体。
在该窗体中添加一个命令按钮和一个文本框,然后设置下列属性:
命令按钮
------------------------
名称:cmdSearch
标题:搜索
单击:事件过程

文本框
--------------
名称:txtSQL
宽度:4.4583"
高度:1.25"
     

将该命令按钮的“单击”属性设置为以下事件过程:
Private Sub cmdSearch_Click()
    On Error Resume Next
   
    Dim ctl As Control
    Dim sSQL As String
    Dim sWhereClause As String
   
    'Initialize the Where Clause variable.
    sWhereClause = " Where "
   
    'Start the first part of the select statement.
    sSQL = "select * from customers "
   
    'Loop through each control on the form to get its value.
    For Each ctl In Me.Controls
        With ctl
            'The only Control you are using is the text box.
            'However, you can add as many types of controls as you want.
            Select Case .ControlType
                Case acTextBox
                    .SetFocus
                    'This is the function that actually builds
                    'the clause.
                    If sWhereClause = " Where " Then
                        sWhereClause = sWhereClause & BuildCriteria(.Name, dbtext, .Text)
                    Else
                        sWhereClause = sWhereClause & " and " & BuildCriteria(.Name, dbtext, .Text)
                    End If
            End Select
        End With
    Next ctl
   
    'Set the forms recordsource equal to the new
    'select statement.
    Me.txtSQL = sSQL & sWhereClause
    Me.RecordSource = sSQL & sWhereClause
    Me.Requery
   
End Sub
     

保存窗体,然后在“窗体”视图中将其打开。
请注意,当您单击“搜索”命令按钮时,“txtSQL”文本框将反映根据“客户”窗体上的值创建的查询。同时,access 还会重新查询“客户”窗体,以使其反映新 SQL 字符串的结果。

(责任编辑:admin)

顶一下
(0)
0%
踩一下
(0)
0%
发表评论
请自觉遵守互联网相关的政策法规,严禁发布色情、暴力、反动的言论。
评价: