Access dynamic filtering listbox with double where clause - vba

I've got a dynamic textbox filtering function in VBA
Dim sSQL As String
sSQL = "SELECT qry_allUtilities.ID, qry_allUtilities.Supplier AS Lieferant, qry_allUtilities.Cabinet AS Ablageort, qry_allUtilities.Size AS Grösse, qry_allUtilities.WorkingLength AS Nutzlänge, qry_allUtilities.Description AS Bezeichnung "
sSQL = sSQL & " FROM qry_allUtilities "
If Not sFilter = "" Then
Dim arrFilter
arrFilter = Split(sFilter, "+")
Dim varWort
For Each varWort In arrFilter
If Not varWort = "" Then
Dim sWort As String
sWort = varWort
sSQL = sSQL & " AND [ID] & ' ' & [Supplier] & ' ' & [Floor] & ' ' & [Cabinet] & ' ' & [Size] & ' ' & [WorkingLength] LIKE '*" & sWort & "*'"
End If
Next
sSQL = Replace(sSQL, " AND ", " WHERE ", 1, 1, vbTextCompare)
End If
ctlListe.RowSource = sSQL
and would like to extend this with another WHERE clause because I have to exclude the records with qry_allUtilities.InActive=False
How do I do this? I always keep getting null or it won't exclude the records with InActive=True :/

I usually do this to add a variable (but unknown) number of filter options:
strFilter = "" ' build the filter string in here
if <first condition reason is true> then
strFilter = strFilter + first condition + " AND "
end if
if <second condition reason is true> then
strFilter = strFilter + <second condition> + " AND "
end if
' finish up
if len(strFilter) > 0 then ' some critera are valid
strFilter = Left(strFilter, Len(strFilter) - 5) ' chop off the spare " AND "
strFilter = " WHERE " + strFilter ' put the " WHERE " on the front
' else ' no where clause
end if
Note that the spaces either side of the " AND " and " WHERE " are important.

Related

How concatenate recordset variables to use filter method - Vba

I would like to concatenate multiple variables on my recordset filter. Here more information :
rs is recordset
titre can be M. or Mme or S. (come from rs)
Nom is of the form (come from rs) : FirstName LastName (with space between)
but I can't. I tried :
space = " "
rs.Filter = "[titre+ space + Nom] = '" & oLookFullName & "' and nomEntreprise = '" & objContact.CompanyName & "'"
Concatenation = rs!titre + " " + rs!Nom
rs.Filter = "Concatenation = '" & oLookFullName & "'"
Any ideas ?
EDIT
#Gustav, I tried your code with split and it seems the filter contains the correct value but just after I have this if loop and in this case rs.EOF is true while the contact exists... why ?
If rs.EOF Then 'Or (rs.BOF = True) Then
Debug.Print oLookFullName & " is not found."
End If
Try with:
rs.Filter = "[titre] & ' ' & [Nom] = '" & oLookFullName & "' And [nomEntreprise] = '" & objContact.CompanyName & "'"
or:
rs.Filter = "[titre] = '" & Split(oLookFullName, " ")(0) & "' And [Nom] = '" & Split(oLookFullName, " ")(1) & "' And [nomEntreprise] = '" & objContact.CompanyName & "'"

Have a List box that Filters on items within my subform that is a query

I have a list box that has three different categories to choose from on the form. I have vba code that is working that allows me to select more than one item in the list box which is fine. But the items I am selecting I am having troubles to get the results that I need.
For an Example; The three categories within the list box are not in the query with the actual category names. One Category I have is called "Picking" okay, I want to select "picking" and then when the button is clicked I want it to pull all Items within the query field "Item Number" that equals '0801' which represents the Category "Picking".
Note the code behind the button is a simple "On Click" Event Procedure
**The List box I am Having troubles with is called (StrAccounts)
**Picking which is the same thing as Acct in the query that I am trying filter on in in tbUpload
**I want the "Picking" Category in the List box to filter on Acct in the query where Acct = '0801'
**Placed_Orders which the Second category name within my ListBox and it is the same field in the query above "tbUpload", Acct, except I want
this Placed_Orders to get all Acct in ('1108', '1114', '1117', '1113',
'1110')
**Whatever Acct in the query tbUpload that doesn't contain the following numbers already mention above is the third category in my
list box which is "Not_Placed"
**So whenever Not_Placed in the list box is clicked and the search button is selected I want Accts in the query to pull, Accts <>
'0801','1108','1114','1117','1113','1110'
Private Sub cmdSearch_Click()
Dim Varitem As Variant
Dim StrDEPT_OBS As String
Dim StrStatus As String
Dim StrACCT As String
Dim strSQL As String
Dim StrAccounts As String
'get selections from DEPT_OBS multiselect listbox
For Each Varitem In Me!List_Dept_OBS.ItemsSelected
StrDEPT_OBS = StrDEPT_OBS & ",'" & Me!List_Dept_OBS.ItemData(Varitem) & "'"
Next
'get selections from Status multiselect listbox
For Each Varitem In Me!List_Status.ItemsSelected
StrStatus = StrStatus & ",'" & Me!List_Status.ItemData(Varitem) & "'"
Next
'get selections from Accts multiselect listbox
For Each Varitem In Me!List_ACCTs.ItemsSelected
StrStatus = StrAccounts & ",'" & Me!List_ACCTs.ItemData(Varitem) & "'"
Next
If Len(StrDEPT_OBS) > 0 Then
StrDEPT_OBS = Right(StrDEPT_OBS, Len(StrDEPT_OBS) - 1)
Else: MsgBox "You must enter an OBS"
Exit Sub
End If
If Len(StrStatus) > 0 Then
StrStatus = Right(StrStatus, Len(StrStatus) - 1)
End If
If Len(StrAccounts) > 0 Then
StrAccounts = Right(StrAccounts, Len(StrAccounts) - 1)
End If
strSQL = " SELECT * FROM tbUpload WHERE "
strSQL = strSQL & "tbUpload.DEPT_ID IN (" & StrDEPT_OBS & ") AND "
If Len(StrStatus) = 0 Then
strSQL = strSQL & "tbUpload.DEPT_ID IN (" & StrDEPT_OBS & ") "
Else
strSQL = strSQL & "tbUpload.OPR_STAT_ID IN (" & StrStatus & ") "
End If
If Len(StrAccounts) = 0 And StrAccounts = "Picking" Then
strSQL = strSQL & "tbUpload.ACCT like (" & [0801] & ")"
Else
End If
If Len(StrAccounts) = 0 And StrAccounts = "Placed_Orders" Then
strSQL = strSQL & "tbUpload.ACCT IN (" & [1108] & [1114] & [1117] & [1113] & [1110] & ") "
Else
strSQL = strSQL & "tbUpload.ACCT <> (" & [0801] & [1108] & [1114] & [1117] & [1113] & [1110] & ") " "Not_Placed"
End If
DoCmd.SetWarnings False
''DoCmd.OpenQuery ("UPLOAD")
Me![tbUpload subform].Form.RecordSource = strSQL
End Sub
If Len(StrAccounts) > 0 Then
'' StrAccounts = Right(StrAccounts, Len(StrAccounts) - 1)
StrAccounts = StrAccounts & ",'" & Me!List_ACCTs.ItemData(Varitem) & "'"
End If
strSQL = " SELECT * FROM tbUpload WHERE "
strSQL = strSQL & "tbUpload.DEPT_ID IN (" & StrDEPT_OBS & ") AND "
If Len(StrStatus) = 0 Then
strSQL = strSQL & "tbUpload.DEPT_ID IN (" & StrDEPT_OBS & ") "
Else
strSQL = strSQL & "tbUpload.OPR_STAT_ID IN (" & StrStat us & ") "
End If
If StrAccounts = "Lugging" Then
strSQL = strSQL & "tbUpload.ACCT like (" & [0801] & ")"
Else
End If
If StrAccounts = "Structure" Then
strSQL = strSQL & "tbUpload.ACCT IN (" & [1108] & [1114] & [1117] & [1113] & [1110] & ") "
Else
End If
Consider:
'get selections from DEPT_OBS multiselect listbox
For Each Varitem In Me.List_Dept_OBS.ItemsSelected
StrDEPT_OBS = StrDEPT_OBS & ",'" & Me.List_Dept_OBS.ItemData(Varitem) & "'"
Next
If Len(StrDEPT_OBS) > 0 Then
StrDEPT_OBS = "[Dept_ID] IN(" & Right(StrDEPT_OBS, Len(StrDEPT_OBS) - 1) & ") AND "
Else
MsgBox "You must enter an OBS"
Exit Sub
End If
'get selections from Status multiselect listbox
For Each Varitem In Me.List_Status.ItemsSelected
StrStatus = StrStatus & ",'" & Me.List_Status.ItemData(Varitem) & "'"
Next
If Len(StrStatus) > 0 Then
StrStatus = "[OPR_STAT_ID] IN(" & Right(StrStatus, Len(StrStatus) - 1) & ") AND "
End If
'get selection from Accts single select listbox and build account parameters array
Select Case Me.List_Accts
Case "Picking"
StrAccounts = "ACCT = 0801 AND "
Case "Placed_Orders"
StrAccounts = "ACCT IN(1108,1114,1117,1113,1110) AND "
Case "Not_Placed"
StrAccounts = "NOT ACCT IN(0801,1108,1114,1117,1113,1110) AND "
End Select
strSQL = StrDEPT_OBS & StrStatus & StrAccounts
If strSQL <> "" Then
strSQL = " WHERE " & Left(strSQL, Len(strSQL) - 5)
End If
Me.[tbUpload subform].Form.RecordSource = "SELECT * FROM tbUpload" & strSQL & ";"
For more info on dynamically building search criteria with VBA, review http://allenbrowne.com/ser-62.html

Combobox filtering for listbox output is not working as expected

I have a few controls (Combobox's I call DDL's) that I use as filters for a dynamic query, shown below.
I have a region, division filter - and BCI/BCV/ABC/etc dropdowns.
When I select the region and division, the output list box correctly filters out everything except THOSE region/divisions. Good.
The problem comes in when I use the other DDL's, ABD/BCI/etc... those do not filter out correctly and I think it is with my and/or clauses below.
Can anyone see anything glaring or point me in the right direction to get this so that every control and ddl element filters out the data it is intended for - while keeping it in a format where the SQL itself is part of a string, like in my example?
Private Sub goBtn_Click()
strSQL = "SELECT [account_number], [BCI_Amt], [BCV_Amt],[ABC_Amt], [other_Amt], " & _
"[BCI_Amt]+[BCV_Amt]+[ABC_Amt]+[other_MRC_Amt], Division_Name, Region_Name, " & _
"Tier, Unit_ID, Name, Description_2 " & _
"FROM dbo_ndw_bc_subs " & _
"WHERE DivisionDDL = [Division_Name] and RegionDDL = [Region_Name] " & _
" and ( [BCI_Ind] = CheckBCI.value or [BCV_Ind] = CheckBCV.value or [ABC_Ind] = CheckABC.value " & _
" or BCIServiceDDL = [Tier]" & _
" or BCVServiceDDL = [Description_2]" & _
" or ABCServiceDDL = [Unit_ID] )" & _
"ORDER BY 6 asc"
Me.output1.RowSource = strSQL
End Sub
One of the combo box DDL control codes. There are check boxes that make the combo box visible or not visible.
Private Sub CheckBCV_Click()
If Me.CheckBCV = vbTrue Then
Me.BCVServiceDDL.Visible = True
Me.BCVServiceDDL = "Select:"
strSQL = "SELECT Distinct subs.[Description_2] FROM dbo_ndw_bc_subs "
Me.BCVServiceDDL.RowSource = strSQL
Me.BCVServiceDDL.Requery
Else
Me.BCVServiceDDL.Visible = False
Me.BCVServiceDDL = ""
End If
End Sub
Edit: Added additional code to the first code block for context, and updated some comments.
To reiterate the point of my question - Since some of the DDL's work as expected while the others do not. Is it in the AND/OR section where I have a problem - or am I forced to do an IF/IIF statement in the select. (And if I do this IF solution - how would that be incorporated into a string the way I have it now, I have not seen an example of this in my research on a resolution).
I think your top code sample should read more like this:
Private Sub goBtn_Click()
Dim strSQL As String
Dim strWhere As String
Dim strOp As String
strSQL = "SELECT [account_number], [BCI_Amt], [BCV_Amt],[ABC_Amt], [other_Amt], " & _
"[BCI_Amt]+[BCV_Amt]+[ABC_Amt]+[other_MRC_Amt], Division_Name, Region_Name, " & _
"Tier, Unit_ID, Name, Description_2 " & _
"FROM dbo_ndw_bc_subs "
strWhere = ""
strOp = ""
If Not IsNull(Me.DivisionDDL.Value) Then
strWhere = strWhere & strOp & "(Division_Name = """ & Me.DivisionDDL.Value & """)"
strOp = " And "
End If
If Not IsNull(Me.RegionDDL.Value) Then
strWhere = strWhere & strOp & "(Region_Name = """ & Me.RegionDDL.Value & """)"
strOp = " And "
End If
If Me.CheckBCI.Value Then
strWhere = strWhere & strOp & "(Tier = """ & Me.BCIServiceDDL.Value & """)"
strOp = " And "
End If
If Me.CheckBCV.Value Then
strWhere = strWhere & strOp & "(Description_2 = """ & Me.BCVServiceDDL.Value & """)"
strOp = " And "
End If
If Me.CheckABC.Value Then
strWhere = strWhere & strOp & "(Unit_ID = """ & Me.ABCServiceDDL.Value & """)"
strOp = " And "
End If
If Len(strWhere) > 0 then
strSQL = strSQL & " WHERE " & strWhere
End If
strSQL = strSQL & " ORDER BY 6 asc"
Me.output1.RowSource = strSQL
End Sub
This is wordier, but much closer to correct. P.S. I guessed that all values are strings. If not remove the quoting around non-string values.

VBA - SQL with optional joins

I have a combolist where I can select multiple values, but if I leave them all blank then I want to exclude that portion from the query. Here is the current logic I'm using
If ModeCat_ID = "" Then
Set rs = conn.Execute("SELECT * FROM [ModeCat_T]")
Else
Set rs = conn.Execute("SELECT * FROM [ModeCat_T] WHERE [ModeCat_ID] = '" & ModeCat_ID & "'")
End If
My question is, is this the best way to go about this? I'm building a form that has a few more options so I'd rather not have a bunch of tested Ifs to check these form controls.
Second question is, if it's a combo box that can select multiples.. how would I set that up for an SQL IN statement? ie
IN ('1','2','3')
Thanks!
EDIT
Set rs = conn.Execute("SELECT * FROM [ModeCat_T]")
This is how I normally do it:
Dim strSQL As String
strSQL = "set nocount on; "
strSQL = strSQL & "select * "
strSQL = strSQL & "from [ModeCat_T] "
strSQL = strSQL & " where 1 = 1 "
'*******************************************************
'* Adding the other where restrictions as necessary
'*******************************************************
If Trim(Sheet1.Range("B7").Value2) <> vbNullString Then
strSQL = strSQL & " and [ModeCat_ID] = '" & Sheet1.Range("B7").Value2 & "' "
End If
If Trim(Sheet1.Range("B8").Value2) <> vbNullString Then
strSQL = strSQL & " and [ModeCat_Color] = '" & Sheet1.Range("B8").Value2 & "' "
End If
If Trim(Sheet1.Range("B9").Value2) <> vbNullString Then
strSQL = strSQL & " and [ModeCat_Size] = '" & Sheet1.Range("B9").Value2 & "' "
End If
Set rs = conn.Execute(strSQL)
Following the continued discussion about "Filters" where you can select possibly many different items from a ListBox the following code might be able to help with that:
Dim strFilter As String
Dim lngItem As Long
For lngItem = 0 To UserForm1.ListBox1.ListCount - 1
If UserForm1.ListBox1.Selected(lngItem) = True Then
If strFilter <> vbNullString Then strFilter = strFilter & ", "
strFilter = strFilter & "'"
strFilter = strFilter & UserForm1.ListBox1.List(lngItem, 1)
strFilter = strFilter & "'"
End If
Next lngItem
If strFilter <> vbNullString Then
strSQL = strSQL & "and [ModeCat_Form] in (" & strFilter & ") "
End If
Basically, it is checking which items from the list have been selected and puts them into a string (wrapped in ' and separated by a comma). Afterwards the code checks if anything made it into the "Filter String". If the filter is not empty then it should be used. BTW: it does not matter if the string contains one or many items. So, this is also permissible:
AND [ModeCat_Shape] in ('Oval')
I felt I should expand my comment the #Ralphs answer with a more maintainable solution.
As you're using a ComboBox and by the sound of it your wanting the user to be able to select multiple columns, use a ListBox instead. I would hide the reference to the field name in the first column of the ListBox by setting it's column width to 0. Then in the next column, you could add the actual filter in there.
Once this is done, you can iterate through the selected items to apply the filters like so:
For i = 0 To ListBox1.ListCount - 1
If ListBox1.Selected(i) Then
strSQL = " AND " & ListBox1.Column(0, i) & " = '" & ListBox1.Column(1, i) & "'"
End If
Next i

open a query based on many choices

hello i wrote this code to open a report based on a query
and this query is based on the toggle button
the problem is if i press one toggle button all work
but if i press more than toggle button in the same time it will not give me the right records or it will give me an empty report
this is the code
DoCmd.SetWarnings False
DoCmd.RunSQL "DELETE * FROM tbl_Mouzakarat"
Dim p_7abes As String
Dim p_gharame As String
Dim p_done As String
Dim p_undone As String
Dim p_khoulasa As String
Dim p_mouzakara As String
Dim p_karar As String
Dim p_jaze2e As String
Dim p_lebanese As String
Dim p_foreign As String
Dim p_SQL_criteria As String
p_7abes = Trim(Me!text_7abes & " ")
p_gharame = Trim(Me!text_gharame & " ")
p_done = Trim(Me!text_done & " ")
p_undone = Trim(Me!text_undone & " ")
p_khoulasa = Trim(Me!text_khoulasa & " ")
p_mouzakara = Trim(Me!text_mouzakara & " ")
p_karar = Trim(Me!text_karar & " ")
p_jaze2e = Trim(Me!text_jaze2e & " ")
p_lebanese = Trim(Me!text_lebanese & " ")
p_foreign = Trim(Me!text_lebanese & " ")
If p_7abes <> "" Then
p_SQL_criteria = "[Punish]" & " LIKE '" & p_7abes & "'"
End If
If p_gharame <> "" Then
p_SQL_criteria = "[Punish]" & " LIKE '*" & p_gharame & "*'"
End If
If p_done <> "" Then
p_SQL_criteria = "[Status_Check]" & " LIKE '*" & p_done & "*'"
End If
If p_undone <> "" Then
p_SQL_criteria = "[Status_Check]" & " LIKE '*" & p_undone & "*'"
End If
If p_khoulasa <> "" Then
p_SQL_criteria = "[Type]" & " LIKE '*" & p_khoulasa & "*'"
End If
If p_mouzakara <> "" Then
p_SQL_criteria = "[Type]" & " LIKE '*" & p_mouzakara & "*'"
End If
If p_karar <> "" Then
p_SQL_criteria = "[Type]" & " LIKE '*" & p_karar & "*'"
End If
If p_jaze2e <> "" Then
p_SQL_criteria = "[Type]" & " LIKE '*" & p_jaze2e & "*'"
End If
If p_lebanese <> "" Then
p_SQL_criteria = "[Nationality]" & " LIKE '*" & p_lebanese & "*'"
End If
If p_foreign <> "" Then
p_SQL_criteria = "[Nationality]" & " NOT LIKE '*" & p_foreign & "*'"
End If
If Me.chk7abes.Value = True Then
DoCmd.RunSQL "INSERT INTO tbl_Mouzakarat select * from " & "[qry_Mouzakarat]" & " where " & p_SQL_criteria
End If
If Me.chkGharame.Value = True Then
DoCmd.RunSQL "INSERT INTO tbl_Mouzakarat select * from " & "[qry_Mouzakarat]" & " where " & p_SQL_criteria
End If
If Me.chkDone.Value = True Then
DoCmd.RunSQL "INSERT INTO tbl_Mouzakarat select * from " & "[qry_Mouzakarat]" & " where " & p_SQL_criteria
End If
If Me.ChkUndone.Value = True Then
DoCmd.RunSQL "INSERT INTO tbl_Mouzakarat select * from " & "[qry_Mouzakarat]" & " where " & p_SQL_criteria
End If
If Me.chkKhoulasa.Value = True Then
DoCmd.RunSQL "INSERT INTO tbl_Mouzakarat select * from " & "[qry_Mouzakarat]" & " where " & p_SQL_criteria
End If
If Me.chkMouzakara.Value = True Then
DoCmd.RunSQL "INSERT INTO tbl_Mouzakarat select * from " & "[qry_Mouzakarat]" & " where " & p_SQL_criteria
End If
If Me.chkKarar7abes.Value = True Then
DoCmd.RunSQL "INSERT INTO tbl_Mouzakarat select * from " & "[qry_Mouzakarat]" & " where " & p_SQL_criteria
End If
If Me.chkKararJaze2e.Value = True Then
DoCmd.RunSQL "INSERT INTO tbl_Mouzakarat select * from " & "[qry_Mouzakarat]" & " where " & p_SQL_criteria
End If
DoCmd.OpenReport "rpt_Mouzakarat", acViewPreview
DoCmd.Close acForm, "frm_Printing"
will someone check the code please
You are overwriting p_SQL_criteria each time then running the same exact query each time no matter how many toggle buttons are pressed.
"INSERT INTO tbl_Mouzakarat select * from " & "[qry_Mouzakarat]" & " where " & p_SQL_criteria
This is always the exact same SQL statement for each of your DoCmd statements.
I'm not really sure how your toggle buttons interact with the parameters you are trying to create so it's hard to suggest solutions, but this is why your having the problem you are having.