Adding multiselect listbox items as a filter in sql statement (1 Viewer)

aman

Registered User.
Local time
Today, 01:15
Joined
Oct 16, 2008
Messages
1,250
Hi Guys

I have a listbox that stores all Campaign types. Its a multiselect listbox so when I select multiple campaign types from the listbox then I want to add that filter in sql statement. How this can be done.

I have tried to write code but it doesn't work. ANy help will be much appreciated.


Code:
Private Sub cmdExport_Click()
 Dim strPath As String
 Dim strName As String
 Dim strFull As String
 Dim intCount As Integer
 Dim NewName As String
 Dim strsql As String
 Dim i As Integer
 Dim a As String
 a = ""
' Fetch multiple campaign types 

 For i = 0 To Me.cboType.ListCount - 1
   If Me.cboType.Selected(i) = True Then
      a = a & "Type=" & Me.cboType.ItemData(i) & " " & "or "
   End If
 Next i

' How to add multiple campaign types filter in the sql below. We will add filter in 'Type' field???"

 strsql = "SELECT tbl_LM_Lead_Mas_Details.*, tbl_LM_Lead_Mas_Customer.*, tbl_LM_Lead_Ref_Campaign.Type FROM (tbl_LM_Lead_Mas_Customer INNER JOIN (tbl_LM_Lead_Mas_Details INNER JOIN tbl_LM_Lead_Ref_CustomerLead ON tbl_LM_Lead_Mas_Details.LeadId = tbl_LM_Lead_Ref_CustomerLead.Leadid) ON tbl_LM_Lead_Mas_Customer.CustomerNo = tbl_LM_Lead_Ref_CustomerLead.CustomerNo) INNER JOIN tbl_LM_Lead_Ref_Campaign ON tbl_LM_Lead_Mas_Details.CampaignId = tbl_LM_Lead_Ref_Campaign.CampaignId WHERE (((tbl_LM_Lead_Mas_Details.LeadStatusId)=1) AND ((tbl_LM_Lead_Mas_Details.AcceptedBy) Is Null));"

 strName = "LM_DailyExport"

   
 NewName = strName

 strFull = CurrentProject.Path & "\" & NewName & ".txt"
  
        
 DoCmd.TransferText acExportDelim, , strsql, FileName:=strFull, hasfieldnames:=False
 MsgBox "Leads exported for " & Me.cboType.Column(1), vbInformation + vbOKOnly, "Export Completed"
 Me.cmdExport.Visible = False
 Me.cmdLeadExportClick.Visible = True
 Me.cboType = ""
End Sub
 

moke123

AWF VIP
Local time
Today, 04:15
Joined
Jan 11, 2013
Messages
3,913
heres a function I use for a multiselect list
Code:
Public Function getLBX(Lbx As ListBox, Optional varColumn As Integer = 0, Optional DeLim As String = ",", Optional TrimEnd As Integer = 1, Optional StringDataType As Boolean = False) As String
'arguments
'Lbx is the name of the listbox
'varColumn is the column number to return
'Delim is the delimiter to use between values
'TrimEnd is the number of spaces to trim off the end of the returned string
'StringDataType is true for strings and false for numerical

    Dim strList As String
    Dim varSelected As Variant

    If Lbx.ItemsSelected.Count = 0 Then
        'MsgBox "You haven't selected anything"
    Else
        For Each varSelected In Lbx.ItemsSelected
        If StringDataType Then
        'its a text string
         strList = strList & Chr(34) & Lbx.Column(varColumn, varSelected) & Chr(34) & DeLim
        Else
        'its numeric
            strList = strList & Lbx.Column(varColumn, varSelected) & DeLim
                End If
        Next varSelected
        strList = Left$(strList, Len(strList) - TrimEnd)
        'MsgBox "You selected the following items:" & vbCrLf & strList
    End If

    getLBX = strList

End Function

this will return a string of the items selected in your listbox. If its string datatype it will return- "Red","Yellow","Blue" - If its numeric - 1,2,3.

to add it to a where clause you would do something like

Code:
Where CampaignType in (" & getLbx(me.MyListBoxName) & ")"

edit: Oops I read your code wrong
 
Last edited:

Cronk

Registered User.
Local time
Today, 18:15
Joined
Jul 4, 2013
Messages
2,772
Firstly, you are trying to export a SQL string ie strSQL. It has to be a table or a saved query.

If you have a saved query say qryYourQuery then you can modify the query in vba and then export the saved query

set db = currentdb
set qdf = db.querydefs("qryYourQuery")
qdf .sql = strSQL
set qdf = nothing
set db = nothing

Secondly include your concatenated multi-list choices in your Where clause you need to add it to your strSQL but because it will have a lot of OR clauses, better if the string is in brackets

strSQL =.......... & " AND (" & a & ")"

However, if you stop your code after the loop concatenating all the values you'll see that there is a trailing OR which will need to be stripped off. I'll leave that to you but come back if you have trouble.
 

aman

Registered User.
Local time
Today, 01:15
Joined
Oct 16, 2008
Messages
1,250
Thanks Moke , I have written the following code . I am getting an issue when trying to export the query result . Looks like it doesn't like strsql in below highlighted statement. If I change strsql to inbuilt query name then it works fine. SO how can I make this bit working. Thanks
Code:
strsql = "select * from qry_LM_Daily_Extract_New_1 where [Type] in (" & strlist & ")"

[COLOR="Red"]DoCmd.TransferText acExportDelim, , strsql, FileName:=strFull, hasfieldnames:=False[/COLOR]
heres a function I use for a multiselect list
Code:
Public Function getLBX(Lbx As ListBox, Optional varColumn As Integer = 0, Optional DeLim As String = ",", Optional TrimEnd As Integer = 1, Optional StringDataType As Boolean = False) As String
'arguments
'Lbx is the name of the listbox
'varColumn is the column number to return
'Delim is the delimiter to use between values
'TrimEnd is the number of spaces to trim off the end of the returned string
'StringDataType is true for strings and false for numerical

    Dim strList As String
    Dim varSelected As Variant

    If Lbx.ItemsSelected.Count = 0 Then
        'MsgBox "You haven't selected anything"
    Else
        For Each varSelected In Lbx.ItemsSelected
        If StringDataType Then
        'its a text string
         strList = strList & Chr(34) & Lbx.Column(varColumn, varSelected) & Chr(34) & DeLim
        Else
        'its numeric
            strList = strList & Lbx.Column(varColumn, varSelected) & DeLim
                End If
        Next varSelected
        strList = Left$(strList, Len(strList) - TrimEnd)
        'MsgBox "You selected the following items:" & vbCrLf & strList
    End If

    getLBX = strList

End Function

this will return a string of the items selected in your listbox. If its string datatype it will return- "Red","Yellow","Blue" - If its numeric - 1,2,3.

to add it to a where clause you would do something like

Code:
Where CampaignType in (" & getLbx(me.MyListBoxName) & ")"

edit: Oops I read your code wrong
 

moke123

AWF VIP
Local time
Today, 04:15
Joined
Jan 11, 2013
Messages
3,913
I read your original question wrong but i believe you can do something along these lines as suggested by Cronk.

In order to use transfer text you need a saved query or table but you can construct a temporary query and use that to transfer.

it would be something along the lines of

Code:
    Dim db As DAO.Database
    Dim qdf As DAO.QueryDef
    Dim strQD As String
    Dim strPath As String
    Dim strName As String
    Dim strFull As String
    Dim strList As String
    
    strList = getLBX(Me.List2, 0) 'get the delimited list from the listbox

    strName = "TestDoc.txt"
    strPath = CurrentProject.Path & "\"
    strFull = strPath & strName

    Set db = CurrentDb

    strQD = "select * from qry_LM_Daily_Extract_New_1 where [Type] in (" & strList & ")"  ' your Sql string
        
    With db.CreateQueryDef("QryTest", strQD) ' create a temporary query named QryTest
    
        DoCmd.TransferText acExportDelim, , "QryTest", FileName:=strFull, hasfieldnames:=False  'execute the transfer text

    End With

    db.QueryDefs.Delete "QryTest"   'Delete the temporary query

    Set qdf = Nothing
    Set db = Nothing
 

aman

Registered User.
Local time
Today, 01:15
Joined
Oct 16, 2008
Messages
1,250
Thanks Moke for all your help. :)
 

Users who are viewing this thread

Top Bottom