I have a listbox that is populated with the following data. I only want to be able to select ( visually ) by the name column.
id | name
1 | value1
2 | value2
I need a few conditions to happen and apply them in a where statement in my SQL.
- If nothing is selected, then just omit the where statement all together
- If 1 value is included, place the where id = 1
If both values are selected, then create an IN statement like the following
IN ('1','2')
EDIT --//
This is the code that populates the listbox upon initialization
Sub UserForm_Initialize()
'SQL query that will populate the Mode Box
Dim cnn As ADODB.Connection
Dim rst As ADODB.Recordset
Set cnn = New ADODB.Connection
Set rst = New ADODB.Recordset
cnn.Open "Provider=SQLOLEDB;Data Source=yadayda;" & _
"Initial Catalog=db;" & _
"Integrated Security=SSPI;"
Set rst = cnn.Execute("SELECT [ID] AS [ID],[Name] AS [Name] FROM [Table]")
rst.MoveFirst
i = 0
With Me.form_mode
.Clear
Do
.AddItem
.List(i, 0) = rst![Mode]
.List(i, 1) = rst![ID]
i = i + 1
rst.MoveNext
Loop Until rst.EOF
End With
rst.Close
cnn.Close
Set rst = Nothing
Set cnn = Nothing
End Sub
EDIT -// Got it to work using the following
`Dim strFilter As String Dim i As Integer
For i = 0 To Main_Window.form_mode.ListCount - 1
If Main_Window.form_mode.Selected(i) Then
If strFilter <> vbNullString Then strFilter = strFilter & ", "
strFilter = strFilter & "'"
strFilter = strFilter & Main_Window.form_mode.List(i, 1)
strFilter = strFilter & "'"
End If
Next i`
Thanks to @ralph in this thread - VBA - SQL with optional joins
excel-vba
but this sounds like an Access form listbox with an SQL rowsource. - ParfaitIN()
for the single selection case. - Tim Williams