简体   繁体   中英

Using textbox values in IN statement

I'm trying to get this to work? How can I set a textbox to be used in an IN() statement? I would like users to be able to list out countries they'd like to query on

SELECT *
FROM Table
WHERE CountryID IN (forms!frmImport!txtCountries)

You can't just put the name of the textbox directly into the SQL string.
Instead, you need to use the content of the textbox to build a SQL string like this:

SELECT * FROM Table WHERE CountryID IN (1,2,3)

If your users enter a comma-separated list of CountryIDs into the textbox, you can build the SQL like this:

Dim SQL As String

SQL = "SELECT * FROM Table WHERE CountryID IN (" & Forms!frmImport!txtCountries & ")"

But I wouldn't do it this way because it's simple, but prone to input errors and SQL injection.

A better way would be to use a list box, set the Multi Select property (so that multiple entries can be selected) and fill it with a list of all available countries.

Then, the user can select the ones that he wants, and you can build the SQL string using the selected items from the listbox:

Dim ListItem As Variant
Dim CountryList As String
Dim SQL As String

For Each ListItem In Forms!frmImport!lstCountries.ItemsSelected
    If CountryList > "" Then
        CountryList = CountryList & ","
    End If
    CountryList = CountryList & ListItem
Next

SQL = "SELECT * FROM Table WHERE CountryID IN (" & CountryList & ")"

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM