會(huì)員登錄 - 用戶注冊(cè) - 網(wǎng)站地圖 Office中國(guó)(office-cn.net),專業(yè)Office論壇
當(dāng)前位置:主頁(yè) > 技巧 > Access技巧 > 查詢視圖 > 正文

在Access中利用搜索窗體中的值生成動(dòng)態(tài)查詢

時(shí)間:2009-08-29 08:40 來(lái)源:網(wǎng)絡(luò) 作者:佚名 閱讀:

有時(shí),您可能需要?jiǎng)?chuàng)建一個(gè)窗體來(lái)用作搜索窗體,以便能夠在窗體上輸入值并動(dòng)態(tài)生成適當(dāng)?shù)?SQL 字符串。下列步驟將向您演示如何動(dòng)態(tài)生成使用 BuildCriteria 方法的查詢字符串。

Microsoft 提供的編程示例只用于演示目的,不附帶任何明示或暗示的保證。這包括但不限于對(duì)適銷性或特定用途適用性的暗示保證。本文假定您熟悉所演示的編程語(yǔ)言以及用于創(chuàng)建和調(diào)試過(guò)程的工具。Microsoft 的支持工程師可以幫助解釋某個(gè)特定過(guò)程的功能,但是他們不會(huì)修改這些示例以提供額外的功能或構(gòu)建過(guò)程以滿足您的特殊需求。警告:執(zhí)行本示例中的步驟將會(huì)修改示例數(shù)據(jù)庫(kù) Northwind.mdb。您可能需要備份 Northwind.mdb 文件,并在該數(shù)據(jù)庫(kù)的副本上執(zhí)行這些步驟。


啟動(dòng) access。
在“幫助”菜單上,指向“示例數(shù)據(jù)庫(kù)”,然后單擊“羅斯文示例數(shù)據(jù)庫(kù)”。
在“設(shè)計(jì)”視圖中打開“客戶”窗體。
在該窗體中添加一個(gè)命令按鈕和一個(gè)文本框,然后設(shè)置下列屬性:
命令按鈕
------------------------
名稱:cmdSearch
標(biāo)題:搜索
單擊:事件過(guò)程

文本框
--------------
名稱:txtSQL
寬度:4.4583"
高度:1.25"
     

將該命令按鈕的“單擊”屬性設(shè)置為以下事件過(guò)程:
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
     

保存窗體,然后在“窗體”視圖中將其打開。
請(qǐng)注意,當(dāng)您單擊“搜索”命令按鈕時(shí),“txtSQL”文本框?qū)⒎从掣鶕?jù)“客戶”窗體上的值創(chuàng)建的查詢。同時(shí),access 還會(huì)重新查詢“客戶”窗體,以使其反映新 SQL 字符串的結(jié)果。

(責(zé)任編輯:admin)

頂一下
(0)
0%
踩一下
(0)
0%
發(fā)表評(píng)論
請(qǐng)自覺(jué)遵守互聯(lián)網(wǎng)相關(guān)的政策法規(guī),嚴(yán)禁發(fā)布色情、暴力、反動(dòng)的言論。
評(píng)價(jià):