【问题标题】:Using values from multi-select list box in MS Access Query在 MS Access Query 中使用多选列表框中的值
【发布时间】:2019-12-18 23:07:39
【问题描述】:

我的 MS Access 数据库中有一个名为 COA_Map 的表。我还有一个带有多选列表框的表单。选择值后,vba 将它们转换为字符串并使用该字符串更新文本框。我想在查询中使用文本框字符串作为变量。

这是我的查询:SELECT * FROM COA_Map WHERE (COA_Map.ASL IN ( [Forms]![Multi-Select Search]![TextASL].Text ) ); 这将返回空结果。当我将文本框值复制并粘贴到这样的查询中时:

SELECT * FROM COA_Map WHERE (COA_Map.ASL IN ( 2.1,2.3,2.4  ) );

我得到了预期的结果。我尝试了[Forms]![Multi-Select Search]![TextASL].Value[Forms]![Multi-Select Search]![TextASL],但出现错误“此表达式输入错误,或者太复杂”

我也尝试使用“OR”子句代替“IN”。我更改了 VBA 以返回此字符串:

构建这个查询:SELECT * FROM COA_Map WHERE COA_Map.ASL = [Forms]![Multi-Select Search]![TextASL] ;

这将返回相同的空结果。当我将文本框值粘贴到这样的查询中时:SELECT * FROM COA_Map WHERE COA_Map.ASL = 2.1 OR COA_Map.ASL = 2.2 OR COA_Map.ASL = 2.3 ; ,我得到了预期的结果。

当在任一版本的查询中只选择一个值时,我会得到预期的结果。

我无法弄清楚为什么从选择了多个值的文本框中读取时查询不会返回结果。

【问题讨论】:

    标签: sql ms-access


    【解决方案1】:

    这是一个通用示例,可​​帮助您朝着正确的方向前进。

    Private Sub cmdOK_Click()
    ' Declare variables
        Dim db As DAO.Database
        Dim qdf As DAO.QueryDef
        Dim varItem As Variant
        Dim strCriteria As String
        Dim strSQL As String
    ' Get the database and stored query
        Set db = CurrentDb()
        Set qdf = db.QueryDefs("qryMultiSelect")
    ' Loop through the selected items in the list box and build a text string
        For Each varItem In Me!lstRegions.ItemsSelected
            strCriteria = strCriteria & ",'" & Me!lstRegions.ItemData(varItem) & "'"
        Next varItem
    ' Check that user selected something
        If Len(strCriteria) = 0 Then
            MsgBox "You did not select anything from the list" _
                , vbExclamation, "Nothing to find!"
            Exit Sub
        End If
    ' Remove the leading comma from the string
        strCriteria = Right(strCriteria, Len(strCriteria) - 1)
    ' Build the new SQL statement incorporating the string
        strSQL = "SELECT * FROM tblData " & _
                 "WHERE tblData.Region IN(" & strCriteria & ");"
    ' Apply the new SQL statement to the query
        qdf.SQL = strSQL
    ' Open the query
        DoCmd.OpenQuery "qryMultiSelect"
    ' Empty the memory
        Set db = Nothing
        Set qdf = Nothing
    End Sub
    

    【讨论】:

      猜你喜欢
      • 2021-05-20
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-12-12
      • 2015-06-18
      • 2014-05-08
      • 2012-06-19
      • 1970-01-01
      相关资源
      最近更新 更多