Using the Like "*" operator in a If Statement - sql

I am trying to create a filter based on four combo boxes that filter records in a subform. The problem is, one value from the RowSource lists on the combo boxes do not exist in the base query.
That value is "All". I was planning to use the same code on all the combo boxes AfterUpdate event. Please see my approach below and advice where necessary. I currently get a type mismatch error on the Me.Combobox1.Value = "Like "*""
If IsNull(Me.combo1.Value) Or IsNull(Me.combo2.Value) Or IsNull(Me.combo3.Value) Or
IsNull(Me.combo4.Value) Then
Exit Sub
End If
If Not IsNull(Me.combo1.Value) Or Not IsNull(combo2.Value) Or Not IsNull(combo3.Value) Or Not
IsNull(combo4.Value) Then
If Me.combo1 = "All" Then
Me.combo1.Value = "Like " * ""
ElseIf Me.combo2.Value = "All" Then
Me.combo2.Value = "Like " * ""
ElseIf Me.combo3.Value = "All" Then
Me.combo3.Value = "Like " * ""
ElseIf Me.combo4.Value = "All" Then
Me.combo4.Value = "Like " * ""
Task1 = "SELECT * FROM qryBase WHERE [Quarter] = '" & Me.combo1.Value & "' AND [CurrentArea] = '" &
Me.combo2.Value & "' AND [CurrentStatus] = '" & Me.combo3.Value & "' AND [MainUser] = '" &
Me.combo4.Value & "'"
End If
End If

As is, your query cannot work as LIKE is meant to replace = in conditional statements. However, LIKE without wildcards behaves like =. Therefore, place the LIKE operator inside the SQL statement.
Dim cbo1, cbo2, cbo3, cbo4 As String
...
If Me.combo1 = "All" Then
cbo1 = "*"
ElseIf Me.combo2.Value = "All" Then
cbo2 = "*"
ElseIf Me.combo3.Value = "All" Then
cbo3 = "*"
ElseIf Me.combo4.Value = "All" Then
cbo4 = "*"
End If
Task1 = "SELECT * FROM qryBase WHERE [Quarter] LIKE '" & cbo1 & "'" _
& " AND [CurrentArea] LIKE '" & cbo2 & "'" _
& " AND [CurrentStatus] LIKE '" & cbo3 & "'" _
& " AND [MainUser] LIKE '" & cbo4 & "'"
Me.frmDatasheet.Form.Recordsource = Task1
Me.frmDatasheet.Form.Requery
However, because combo boxes can have apostrophes, consider parameterization to avoid need of concatenating VBA values directly into SQL but bind them as parameters:
Dim qdef As QueryDef
Dim rst As Recordset
Dim sql AS String
Dim cbo1, cbo2, cbo3, cbo4 As String
sql = "PARAMETERS cbo1 TEXT, cbo2 TEXT, cbo3 TEXT, cbo4 TEXT;" _
& "SELECT * FROM qryBase WHERE [Quarter] LIKE [cbo1]" _
& " AND [CurrentArea] LIKE [cbo2]" _
& " AND [CurrentStatus] LIKE [cbo3]" _
& " AND [MainUser] LIKE [cbo4]"
If Me.combo1 = "All" Then
cbo1 = "*"
ElseIf Me.combo2.Value = "All" Then
cbo2 = "*"
ElseIf Me.combo3.Value = "All" Then
cbo3 = "*"
ElseIf Me.combo4.Value = "All" Then
cbo4 = "*"
End If
' INITIALIZE QUERY OBJECT
Set qdef = CurrentDb.CreateQueryDef("", sql)
' Set qdef = CurrentDb.QueryDefs("mySavedParamQuery")
' BIND PARAMS
qdef!cbo1 = cbo1
qdef!cbo2 = cbo2
qdef!cbo3 = cbo3
qdef!cbo4 = cbo4
' SET FORM RECORDSET TO EXECUTED QUERY
Set rst = qdef.OpenRecordset()
Set Me.frmDatasheet.Form.Recordset = rst
Set rst = Nothing: Set qdef = Nothing

Related

How do I exlude records from my database if a checkbox is false?

I have this split form with some basic search functions based on comboboxes and search fields. Now I want to exclude the records where my checkbox chk_NonC = false.
The VBA-code I currently use to filter my record source qry_Administration:
Function SearchCriteria()
Dim Customer, CustomerLocation, CustomerLocationPlace, ExecutionDate, Material As String
Dim Intern, Extern As String
Dim task, strCriteria As String
If Me.chk_AuditEX = True Then
Extern = "[AuditEX] = " & Me.chk_AuditEX
Else
Extern = "[AuditEX] like '*'"
End If
If Me.chk_AuditIN = True Then
Intern = "[AuditIN] = " & Me.chk_AuditIN
Else
Intern = "[AuditIN] like '*'"
End If
If IsNull(Me.cbo_CustomerLocations) Then
CustomerLocation = "[CustomerLocationID] like '*'"
CustomerLocationPlace = "[LocationCompanyPlace] like '*'"
Else
CustomerLocation = "[LocationCompanyName] = '" & Me.cbo_CustomerLocations.Column(0) & "'"
CustomerLocationPlace = "[LocationCompanyPlace] = '" & Me.cbo_CustomerLocations.Column(1) & "'"
End If
If IsNull(Me.cbo_Customers) Then
Customer = "[CustomerID] like '*'"
Else
Customer = "[CustomerID] = " & Me.cbo_Customers
End If
If IsNull(Me.txt_ExecutionDateTo) Then
ExecutionDate = "[ExecutionDate] like '*'"
Else
If IsNull(Me.txt_ExecutionDateFrom) Then
ExecutionDate = "[ExecutionDate] like '" & Me.txt_ExecutionDateTo & "'"
Else
ExecutionDate = "([ExecutionDate] >= #" & Format(Me.txt_ExecutionDateFrom, "mm/dd/yyyy") & "# And [ExecutionDate] <= #" & Format(Me.txt_ExecutionDateTo, "mm/dd/yyyy") & "#)"
End If
End If
If IsNull(Me.cbo_Material) Or Me.cbo_Material = "" Then
Material = "[MaterialID] like '*'"
ElseIf Me.cbo_Material = 6 Then
Material = "[MaterialID] in (" & TempVars!tempMaterial & ")"
Else
Material = "([MaterialID] = " & Me.cbo_Material & ")"
End If
strCriteria = Customer & "And" & CustomerLocation & "And" & CustomerLocationPlace & "And" & _
& ExecutionDate & Material & "And" & Extern & "And" & Intern
task = "Select * from qry_Administration where (" & strCriteria & ") order by ExecutionDate DESC"
Debug.Print (task)
Me.Form.RecordSource = task
Me.Form.Requery
End Function
Now I want to add this new checkbox Non-Compliant named chk_NonC
When I set chk_NonC to true and press search I want my split-form to show all records.
When I set chk_NonC to false and press search I want my split-form to hide all records where Non_compliant is true
You can see it as a hide function for my database. If I set this checkbox to false then hide all records where non-compliant is set to true.
Please note that function SearchCriteria is called on the OnChange Events of the comboboxes or by clicking a search-icon on the top of my split-form.
Just follow the same flow defined for the other controls.
Create the string portion for the compliance and append it to the rest of the sql script.
Dim strCompliant As String
strCompliant = IIf(Me.chk_NonC,"[Non_compliant]=True","[Non_compliant]=False")
strCriteria = Customer & " And " [...] & " And " & strCompliant
Keep in mind, you need spaces between the " And " joins in strCriteria.

Unable to Filter

I am trying to write an SQL code in my MS Access database whereby the filter on Entity_name is not working properly
Function FilterResults()
Dim strCriteria As String
strCriteria = ""
If Nz(Me.cboEntitynameFilter) <> "" Then
strEntityNameFilter = "Entity_Name = '" & Me.cboEntitynameFilter & "'"
Else
strEntityNameFilter = "Entity_Name = '*'"
End If
If Nz(Me.cboAssignmentFilter) <> "" Then
strAssignmentFilter = " AND " & "Assignment = '" & Me.cboAssignmentFilter & "'" '& " AND "
End If
If Nz(Me.cboFYFilter) <> "" Then
strFYFilter = " AND " & "Financial_Year = '" & Me.cboFYFilter & "'"
End If
strCriteria = Nz(strEntityNameFilter, "*") & Nz(strAssignmentFilter, "*") & Nz(strFYFilter, "*")
' End If
If strCriteria = ("Entity_Name = '*'") Then
Me.Filter = ""
Me.FilterOn = False
Else
If strCriteria <> "" Then
Me.Filter = strCriteria
Me.FilterOn = True
End If
End If
End Function
The strCriteria returned is
Entity_Name = '*' AND Assignment = 'MFI'
The filter doesn't work and the Entity_Name is all blank. What am I doing wrong.
I am using this in MS-Access and building query in VBA
I would do like this
Dim strCriteria AS string
strCriteria = "1 = 1"
If Len(Nz(Me.cboEntitynameFilter, "")) > 0 Then
strCriteria = strCriteria & " and [Entity_Name] = """ & Me.cboEntitynameFilter & """"
End If
If Len(Nz(Me.cboAssignmentFilter, "")) > 0 Then
strCriteria = strCriteria & " and [Assignment] = """ & Me.cboAssignmentFilter & """"
End If
If Len(Nz(Me.cboFYFilter, "")) > 0 Then
strCriteria = strCriteria & " and [Financial_Year] = """ & Me.cboFYFilter & """"
End If
Me.Filter = strCriteria
Me.FilterOn = True
if any of the combobox or textbox didn't select than it will igonre those field.

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.

MS-Access Update SQL Not Null But is Blank (! Date & Number Fields !)

I have a few controls that are number and short date format in my tables also the date controls are masked to mm/dd/yyyy. Some of the fields that are loaded into the form are blank from the original table and so when executing the sql I am essentially evaluating the wrong thing whether Im checking for '' or Null. as '' fails as text for date number and the fields are not actually blank.
strSQL4 = "UPDATE [tblDetails] SET " & _
"[Proposed] = IIF(IsNull(" & Forms!frmEdit.txtProposed.Value & "),0," & Forms!frmEdit.txtProposed.Value & "), " & _
"[Multi] = IIF(IsNull(" & Forms!frmEdit.txtMulitplier.Value & "),0," & Forms!frmEdit.txtMulitplier.Value & "), " & _
"[Rational] = '" & Forms!frmEdit.txtRational.Value & "' " & _
" WHERE [RNumber] = '" & Forms!frmEdit.cmbUpdate.Value & "'"
Debug.Print strSQL4
dbs.Execute strSQL4
ERROR 3075 Wrong number of arguments used with function in query expression
'IIF(IsNull(),0,'
I also tried entering the field itself suggested from another site
strSQL4 = "UPDATE [tblDetails] SET " & _
"[Proposed] = IIF(" & Forms!frmEdit.txtProposed.Value & "='',[Proposed]," & Forms!frmEdit.txtProposed.Value & "), " & _
" WHERE [RNumber] = '" & Forms!frmEdit.cmbUpdate.Value & "'"
Debug.Print strSQL4
dbs.Execute strSQL4
Same Error 3075 'IIF(IsNull(),0,[ProposedHrs]'
***also fails if I use the IIF(IsNull method as opposed to the =''
I did not paste an example of the dates failing, but is the same idea, not null but is blank, but cant seem to update back to blank again or even skip maybe?
Thanks to anyone in advance.
Update-1 from attempting Erik Von Asmuth code <--Thanks btw!
Set qdf = db.CreateQueryDef("", & _
"UPDATE [tblDetails] SET " & _
"[Proposed] = #Proposed, " & _
"[Multi] = #Multi, " & _
"[Rational] = #Rational " & _
"WHERE [RNumber] = #RNumber")
This portion is all red and the first "&" is highlighted after closing the notification window
Compile error:
Expected: expression
Update-2: I moved the update to the first line and it seems to be working. Set qdf = db.CreateQueryDef("", "UPDATE [tblDetails] SET " & _
I am going to try this method with the dates fields next.
Update-3: when attempting the same parameterization with textbox's masked with 99/99/0000;0;_ I am receiving item not found in collection? I have checked the spelling several times and everything seems ok. I tried the following three formats so set parameter DateRcvd, can anyone comment if this is correct for a text box with dates?
qdf.Parameters("#DateRcvd") = IIf(Nz(Forms!frmEdit.txtDateRcvd.Value) = "", 0, Forms!frmEdit.txtDateRcvd.Value)
qdf.Parameters("#DateRcvd") = IIf(IsNull(Forms!frmEdit.txtDateRcvd.Value), 0, Forms!frmEdit.txtDateRcvd.Value)
qdf.Parameters("#DateRcvd") = IIf(Forms!frmEdit.txtDateRcvd.Value = "", 0, Forms!frmEdit.txtDateRcvd.Value)
Update-4:
Dim qdf2 As DAO.QueryDef
Set db = CurrentDb
Set qdf2 = db.CreateQueryDef("", "UPDATE [tblDetails] SET " & _
"[DateReceived] = #DateRcvd " & _
"WHERE [RNumber] = #RNumber")
qdf.Parameters("#DateRcvd") = IIf(Nz(Forms!frmEdit.txtDateRcvd.Value) = "", 0, Forms!frmEdit.txtDateRcvd.Value)
qdf.Parameters("#RNumber") = Forms!frmEdit.cmbUpdate.Value
qdf2.Execute
Please Note text box txtDateRcvd has an Input Mask 99/99/0000;0;_ set within the properties of the textbox.
You should account for empty strings, and do that IIF statement in VBA instead of SQL:
strSQL4 = "UPDATE [tblDetails] SET " & _
"[Proposed] = " & IIF(Nz(Forms!frmEdit.txtProposed.Value) = "",0, Forms!frmEdit.txtProposed.Value) & ", " & _
"[Multi] = " & IIF(Nz(Forms!frmEdit.txtMulitplier.Value) = "",0, Forms!frmEdit.txtMulitplier.Value) & ", " & _
"[Rational] = '" & Forms!frmEdit.txtRational.Value & "' " & _
" WHERE [RNumber] = '" & Forms!frmEdit.cmbUpdate.Value & "'"
Or better yet, do it properly and parameterize the whole update so you can't get these kind of errors or SQL injection.
Example of how to do it properly:
Dim db As DAO.Database
Dim qdf As DAO.QueryDef
Set db = CurrentDb
Set qdf = db.CreateQueryDef("", _
"UPDATE [tblDetails] SET " & _
"[Proposed] = #Proposed, " & _
"[Multi] = #Multi, " & _
"[Rational] = #Rational " & _
"WHERE [RNumber] = #RNumber"
)
qdf.Parameters("#Proposed") = IIF(Nz(Forms!frmEdit.txtProposed.Value) = "",0, Forms!frmEdit.txtProposed.Value)
qdf.Parameters("#Multi") = IIF(Nz(Forms!frmEdit.txtMulitplier.Value) = "",0, Forms!frmEdit.txtMulitplier.Value)
qdf.Parameters("#Rational") = Forms!frmEdit.txtRational.Value
qdf.Parameters("#RNumber") = Forms!frmEdit.cmbUpdate.Value
qdf.Execute

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