Link to home
Start Free TrialLog in
Avatar of Sandra Smith
Sandra SmithFlag for United States of America

asked on

Loop through listbox items and place in sql statement

I have a combobox that as the user selects items, they poulate a listbox.  So, say the user selects four merchants from the combobox and these are now items in the listbox.  However, these are general names and the sql query really needs them to be in a like statement.  So, I need to loop through the listbox items and build a like statement.  I have attached what I have come up with so far.!  How do I tell it to delete the last OR at the end of the string?  .  That is, this is correct:
 Like '*MERCHANT ONE*' OR  Like 'MERCHANT TWOr*' OR  Like '*MERCHANT THREE   '*' OR  Like '*MERCHANT FOUR*' OR

but I don't need, naturally, the final OR and extra spaces
Private Sub WhereLikeString()
'If there is more than one item in the listbox, then need to create like strings for each item
'in the list box as a parameter to the sql statement
Dim i           As Integer
Dim strWhere    As String
Dim varItem     As Variant

i = Me.lstMerchants.ListCount
If i < 1 Then
    Exit Sub
End If


Dim strArray() As String
'    Dim i As Integer
    For i = 0 To lstMerchants.ListCount - 1
        ReDim Preserve strArray(i)
        strArray(i) = lstMerchants.ItemData(i)
        Debug.Print strArray(i)
        strWhere = strWhere & " Like '" & strArray(i) & "' OR "
        Debug.Print strWhere
    Next i

Ebd Syb

Open in new window

ASKER CERTIFIED SOLUTION
Avatar of omgang
omgang
Flag of United States of America image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of Sandra Smith

ASKER

that works. Am posting another question as have discovered some of the merchant names have apostrophe in them and I need to clear that out of each name before it is used in the where clause.