【发布时间】:2018-08-27 21:28:21
【问题描述】:
我试图通过使用 VBA 设置 listbox.rowsource 在 msAccess 的列表框中获取过滤列表。以下代码示例具有解释我尝试过的所有内容的 cmets。要运行代码,请创建一个小表“tblsop”,其中包含与 SQL 列匹配的两个字段,这两个字段都是文本。然后取消注释设置 searchSQL 的各种尝试
Private Sub Form_Open(Cancel As Integer)
Dim searchSQL As String
' the following commented out versions of setting searchSQL show what I
' have tried and what works vs what doesn't work. I can't find a version
' of setting searchSQL = that works. forms!frmSearch.txt1 evaluates to
' the string chem in my testing
' this displays the whole table of rows in the listbox of this form
' searchSQL = "select sopid, sopname, soplink from tblSOP"
' this works also just to show it is not only adding a where that kills it
' searchSQL = "select sopid, sopname, soplink from tblSOP where 1=1"
' the next two display empty listbox with no columns
' searchSQL = "select sopid, sopname, soplink from tblSOP where sopName like ""*" & Forms!frmsearch.txt1.Value & "*"""
' debug.print searchSQL = select sopid, sopname, soplink from tblSOP where sopName like "*chem*"
' searchSQL = """select sopid, sopname, soplink from tblSOP where sopName like ""*" & Forms!frmsearch.txt1.Value & "*"""""
' debug.print searchSQL = "select sopid, sopname, soplink from tblSOP where sopName like "*chem*""
' this one I got from a web answer to another question so I tried the # as delimiters
' this one displayed 2 columns but they were empty
' searchSQL = "select sopid, sopname, soplink from tblSOP where sopName like #*" & Forms!frmsearch.txt1.Value & "*#"
' debug.print = select sopid, sopname, soplink from tblSOP where sopName like #*chem*#
resultsList.RowSource = searchSQL
' I have tried resultsList.requery here and also several variations of
' resultslist.recordsourcetype to no avail. A test of the last two searchSQL
' variations using a testSQL(searchSQL) routine works fine showing two records
' in the immediate window. somehow programatically setting rowsource evaluates quotes
' differently than sending it with openrecordset() (used in testsql)
End Sub
【问题讨论】:
-
#HansUp 2. 正如我在注释中所说,当在 rowsourxce 之外的任何地方完成时,即时窗口中的查询会返回正确的结果
-
我已经重做这个以使用 sql 语句创建一个 queryDef。我删除了永久的 querydef searchSOP,然后使用字段值通过 SQL 重新创建它。我有。验证当我更改字段的值时,queryDef 会更改。在通过搜索运行程序后,我打开了 queryDef,新的 queryDef 具有预期的新值并且按预期工作,但是当我运行程序时,如果我的 sql 没有 where 子句,它设置 rowsource = "searchSOP" 它可以工作如果我添加 where 子句,它不会显示任何值,尽管查询是独立的