问题
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)
回答1:
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 & ")"
来源:https://stackoverflow.com/questions/24127816/using-textbox-values-in-in-statement