Form with multi-criteria searches - uses strings and filters - vba

I have a search form with blank fields tied to a table, four criteria search boxes, and a button to take the input from the search boxes, search the table, and populate the results on the form's blank fields.
As of now, it works as long as all four criteria boxes aren't null.
I used filters to achieve this, and here's the code that works as long as all four boxes are not empty. (My criteria boxes are as follows: a textbox called "Keyword" and three combo boxes called HRCombo, BuildingCombo, and RoomCombo, and the fields they're tied to are as follows: "Item Description" "HR Holder" "Building" "Room") My first line "Me.Filter = ..." was broken up to make it easier to view.
Me.Filter = "[Item Description] Like " & Chr(34) & Me.Keyword & "*" & Chr(34) & "
AND [HR Holder] = '" & Me.HRCombo & "'" & " AND [Building] = '" & Me.BuildingCombo
& "'" & " AND [Room] = '" & Me.RoomCombo & "'"
Me.FilterOn = True
Me.Requery
I need it to be able to do the search no matter which combination of criteria boxes have input. Someone recommended using if statements to do the following:
Create four strings, one for each criteria box. Use 4 if statements to check if the box is null - if it is null, assign an asterisk to its string, and if its not null, assign the value I used for the above Me.Filter statement to each box's string. Then, use Me.Filter and concatenate the four strings at the end.
Here's the code I used for this, and, with my limited knowledge, I can't get it to work.
Dim StrA as String, StrB as String, StrC as String, StrD as String
If Me.Keyword is null then
StrA = "*"
else
StrA = [Item Description] Like " & Chr(34) & Me.Keyword & "*" & Chr(34)
End If
If Me.HRCombo is null then
StrB = "*"
else
StrB = [HR Holder] = '" & Me.HRCombo & "'"
End If
If Me.BuildingCombo is null then
StrC = "*"
else
StrC = [Building] = '" & Me.BuildingCombo & "'"
End If
If Me.RoomCombo is null then
StrD = "*"
else
StrD = [Room] = '" & Me.RoomCombo & "'"
End If
Me.Filter = "StrA & " AND "StrB & " AND "StrC &" AND "StrD"
Me.FilterOn = True
Me.Requery
Like I said, I have a limited knowledge, so I'm sure there's probably missing quotes and commas, or too many of them. Any ideas?

You're missing some important quotes and your logic to check for null is correct for SQL but not correct for VBA. I'm posting here what I believe is a cleaner way of doing this. Just be aware that you're not escaping single quotes that might be entered in your controls and neither am I in this code (except in the first one, just so you can see how to do it using the Replace function). That's a pretty important thing to do any time a single quote could possibly land up in one of the search/filtering controls.
Dim strWhere as String
If Nz(Me.Keyword, "") <> "" Then
strWhere = strWhere & "[Item Description] Like '*" & Replace(Me.Keyword, "'", "''") & "*' AND "
End If
If Nz(Me.HRCombo, "") <> "" Then
strWhere = strWhere & "[HR Holder] = '" & Me.HRCombo & "' AND "
End If
If Nz(Me.BuildingCombo, "") <> "" Then
strWhere = strWhere & "[Building] = '" & Me.BuildingCombo & "' AND "
End If
If Nz(Me.RoomCombo, "") <> "" Then
strWhere = strWhere & "[Room] = '" & Me.RoomCombo & "' AND "
End If
If strWhere <> "" Then
strWhere = Left(strWhere, Len(strWhere)-5) 'Remove the extra AND
Me.Filter = strWhere
Me.FilterOn = True
Else
Me.Filter = ""
Me.FilterOn = False
End If

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.

Grouping records in a combobox on split-form with the same "string value" but different ID's

I know I can do this with multivalue fields, but this causes other problems.
I have a main split-form with comboboxes to sort all kinds of different combinations. For example, I have a cbo_Customers, cbo_CustomerLocations, etc... (see VBA code at bottom)
The same CustomerLocation can have different Customers. So it is possible to have 2 different Customers which have the same CustomerLocation.
In my main split-form I have a combobox named cbo_CustomerLocations which looks up values from tbl_CustomerLocations.
tbl_CustomerLocations consists of 4 fields. CustomerLocationID, LocationCompanyName, LocationCompanyPlace, CustomerID (which is linked to tbl_Customers)
I have 1 location named: TESTLOCATION,
I have 2 Customers named: CUSTOMER_1 and CUSTOMER_2
I tried to avoid multivalue fields, so therefore
in tbl_CustomerLocations the record with value TESTLOCATION is twice in this table because the field CustomerID is linked to CUSTOMER_1 and the other record linked to CUSTOMER_2
Now in my main form in combobox cbo_CustomerLocations this TESTLOCATION is also shown twice (2 different CustomerLocationID)
I want this combobox to GROUP BY CustomerLocationName. And, if I select this (grouped) TESTLOCATION
my form must show all records where string "TESTLOCATION" is found. (TESTLOCATION has different ID's)
This is my SQL where TESTLOCATION is shown twice:
SELECT tbl_CustomerLocations.CustomerLocationID,
tbl_CustomerLocations.LocationCompanyName,
tbl_CustomerLocations.LocationCompanyPlace
FROM tbl_CustomerLocations
ORDER BY tbl_CustomerLocations.LocationCompanyName;
I tried something like:
SELECT Count(tbl_CustomerLocations.CustomerLocationID) AS
CountOfCustomerLocationID, tbl_CustomerLocations.LocationCompanyName
FROM tbl_CustomerLocations
GROUP BY tbl_CustomerLocations.LocationCompanyName;
This does combine TESTLOCATION in the combobox, but my records do not show up in my split-form
I also tried this, found on Stack Overflow:
SELECT * FROM tbl_CustomerLocations e1, tbl_CustomerLocations e2
WHERE e1.LocationCompanyName = e2.LocationCompanyName
AND e1.CustomerLocationID != e2.CustomerLocationID;
This is also a dead end.
In my main split-form, after I update combobox cbo_CustomerLocations the following VBA code is called:
Private Sub cbo_CustomerLocations_AfterUpdate()
Call SearchCriteria
End Sub
Function SearchCriteria()
Dim Customer, CustomerLocation as String
Dim task, strCriteria As String
If IsNull(Me.Cbo_Customers) Then
Customer = "[CustomerID] like '*'"
Else
Customer = "[CustomerID] = " & Me.Cbo_Customers
End If
If IsNull(Me.cbo_CustomerLocations) Then
CustomerLocation = "[CustomerLocationID] like '*'"
Else
CustomerLocation = "[CustomerLocationID] = " & cbo_CustomerLocations
End If
strCriteria = Customer & "And" & CustomerLocation
task = "Select * from qry_Administration where (" & strCriteria & ")"
Me.Form.RecordSource = task
Me.Form.Requery
So basically I want to select the (grouped) TESTLOCATION in cbo_CustomerLocations. Then function SearchCriteria is called and my form shows all records where string TESTLOCATION is found.
TESTLOCATION has different ID's.
I guess I also have to edit these lines in some way?
strCriteria = Customer & "And" & CustomerLocation
task = "Select * from qry_Administration where (" & strCriteria & ")"
because strCriteria gives problems with this grouped field?
I know it is a lot of information, but I try to be as clearly as possible.
If I'm understanding correctly, you want the cbo_CustomerLocations combobox in the main form to contain a list of distinct customer locations. Upon selecting a value, you want the subform to be filtered so that only customers in the selected location appear, yes? Here's what I would recommend:
Combobox:
tbl_CustomerLocations contains data such as this:
CustomerLocationID
LocationCompanyName
LocationCompanyPlace
CustomerID
1
Company A
Netherlands
1
2
Company B
Netherlands
2
3
Company C
England
4
4
Company D
Spain
5
5
Company E
England
16
You want the combobox to contain this list:
LocationCompanyPlace
England
Netherlands
Spain
To achieve this, the data source for your combobox should be as follows:
SELECT LocationCompanyPlace
FROM tbl_CustomerLocations
GROUP BY LocationCompanyPlace
OR
SELECT DISTINCT LocationCompanyPlace
FROM tbl_CustomerLocations
GROUP BY LocationCompanyPlace
(Both of the above queries should return the same results.)
Now, you'll need to update your VBA code.
Sub cbo_CustomerLocations_AfterUpdate():
(No changes needed)
Private Sub cbo_CustomerLocations_AfterUpdate()
Call SearchCriteria
End Sub
Function SearchCriteria():
Function SearchCriteria()
Dim Customer, CustomerLocation as String
Dim task, strCriteria As String
Dim recordSource As string
If IsNull(Me.Cbo_Customers) = False Then 'If a Customer is selected, filter by selected Customer
recordSource = "SELECT * FROM qry_Administration WHERE [CustomerID] = " & Me.Cbo_Customers
Else 'If a Customer is NOT selected, check to see if a CustomerLocation is selected
If IsNull(me.cbo_CustomerLocations) = False Then 'If a Customer Location is selected, filter by selected CustomerLocation
'Use this line if the CustomerLocationPlace field exists in qry_Administration
recordSource = "SELECT * FROM qry_Administration WHERE [CustomerLocationPlace]='" & Me.Cbo_CustomerLocations & "'"
'Use the recordSource below if the CustomerLocationPlace field DOES NOT exist in qry_Administration
'This line joins qry_Administration to the tbl_CustomerLocations table so that you can filter on the CustomerLocationPlace field
'By using "SELECT a.*", only records from qry_Administration are returned
'recordSource = "SELECT a.* FROM qry_Administration a INNER JOIN dbo.tbl_CustomerLocations l ON a.CustomerID = l.CustomerID WHERE l.CustomerLocationPlace='" & Me.Cbo_CustomerLocations & "'"
Else 'If neither a Customer nor a Customer Location are selected, return all records in qry_Administration
recordSource = "SELECT * FROM qry_Administration"
End If
End If
Me.Form.RecordSource = recordSource
Me.Form.Requery
End Function
I have included comments to explain the code above, but please note that you may need to adjust the code in the If part of the nested if statement. If the CustomerLocationPlace field exists in qry_Administration, then you may use the code as is. However, if the CustomerLocationPlace field does NOT exist in qry_Administration, then you should comment out line 12 (recordSource = "SELECT * FROM qry_Administration WHERE [CustomerLocationPlace]='" & Me.Cbo_CustomerLocations & "'") & uncomment line 17 ('recordSource = "SELECT a.* FROM qry_Administration a INNER JOIN dbo.tbl_CustomerLocations l ON a.CustomerID = l.CustomerID WHERE l.CustomerLocationPlace='" & Me.Cbo_CustomerLocations & "'").
I believe this solution should address your problem. If you have any questions or concerns, let me know.
With a little editing of your solution I managed to get it working.
The solution with grouped combobox works. You were also correct about CustomerLocationPlace being part of the query. I did not use the CustomerLocationPlace field, but I used the CustomerLocationName field instead. I also had to add the following line:
CustomerLocationPlace = "[LocationCompanyPlace] = '" & Me.cbo_CustomerLocations.Column(1) & "'"
I stripped my VBA so it was more easier for you guys. My script was a little bit more complicated then I posted earlier. I did use your solution, but I left my VBA script intact like I had before. Just for explaining purpose here is my full VBA script of function StrCriteria with the solution of David Buck implemented:
Function SearchCriteria()
Dim Customer, CustomerLocation, CustomerLocationPlace, Protocol, SampleProvider, BRL, ProjectLeader, LabNumber, ExecutionDate, Classification, SampleProvider2, Material As String
Dim Extern, Intern As String
Dim strText, strSearch As String
Dim task, strCriteria As String
Me.FilterOn = True
If IsNull(Me.txt_Search) Or Me.txt_Search = "" Then
strText = "[DataID] like '*'"
Else
strSearch = Me.txt_Search.Value
strText = "(LabNumberPrimary like ""*" & strSearch & "*"")" & "Or" & _
"(LabNumber_2_MH like ""*" & strSearch & "*"")" & "Or" & _
"(LabNumber_3_ASB like ""*" & strSearch & "*"")" & "Or" & _
"(LabNumber_4_CT like ""*" & strSearch & "*"")" & "Or" & _
"(LabNumber_5_LA like ""*" & strSearch & "*"")" & "Or" & _
"(LabNumber_6_CBR like ""*" & strSearch & "*"")" & "Or" & _
"(HerkeuringNumber like ""*" & strSearch & "*"")" & "Or" & _
"(Protocol like ""*" & strSearch & "*"")" & "Or" & _
"(BRL like ""*" & strSearch & "*"")" & "Or" & _
"(PrincipalCompanyName like ""*" & strSearch & "*"")" & "Or" & _
"(ProjectLeaderName like ""*" & strSearch & "*"")" & "Or" & _
"(Material like ""*" & strSearch & "*"")" & "Or" & _
"(Classification like ""*" & strSearch & "*"")" & "Or" & _
"(PrincipalContactName like ""*" & strSearch & "*"")" & "Or" & _
"(LocationContactName like ""*" & strSearch & "*"")" & "Or" & _
"(SampleProviderName like ""*" & strSearch & "*"")" & "Or" & _
"(QuotationNumber like ""*" & strSearch & "*"")" & "Or" & _
"(LocationCompanyName like ""*" & strSearch & "*"")"
End If
If Me.chk_Ex = True Then
Extern = "[AuditExID] = 2"
Else
Extern = "[AuditExID] like '*'"
End If
If Me.chk_In = True Then
Intern = "[AuditInID] = 2"
Else
Intern = "[AuditInID] like '*'"
End If
If IsNull(Me.cbo_CustomerLocations) Then
CustomerLocation = "[CustomerLocationID] 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.cbo_Protocol) Or Me.cbo_Protocol = "" Then
Protocol = "[ProtocolID] like '*'"
ElseIf Me.cbo_Protocol = 5 Then
Protocol = "[ProtocolID] in (" & TempVars!tempProtocol & ")"
Else
Protocol = "([ProtocolID] = " & Me.cbo_Protocol & ")"
End If
If IsNull(Me.cbo_Classification) Or Me.cbo_Classification = "" Then
Classification = "[ClassificationID] like '*'"
ElseIf Me.cbo_Classification = 5 Then
Classification = "[ClassificationID] in (" & TempVars!tempClassification & ")"
Else
Classification = "([ClassificationID] = " & Me.cbo_Classification & ")"
End If
If IsNull(Me.cbo_SampleProviders) Or Me.cbo_SampleProviders = "" Then
SampleProvider = "[SampleProviderPrimaryID] like '*'"
ElseIf Me.cbo_SampleProviders = 6 Then
SampleProvider = "[SampleProviderPrimaryID] in (" & TempVars!tempSampleProviders & ")"
Else
SampleProvider = "([SampleProviderPrimaryID] = " & Me.cbo_SampleProviders & ")"
End If
If IsNull(Me.cbo_SampleProviders2) Then
SampleProvider2 = "[SampleProviderSecondaryID] like '*'"
Else
SampleProvider2 = "[SampleProviderSecondaryID] = " & Me.cbo_SampleProviders2
End If
If IsNull(Me.cbo_BRL) Or Me.cbo_BRL = "" Then
BRL = "[BRLID] like '*'"
ElseIf Me.cbo_BRL = 5 Then
BRL = "[BRLID] in (" & TempVars!tempBRL & ")"
Else
BRL = "([BRLID] = " & Me.cbo_BRL & ")"
End If
If IsNull(Me.cbo_ProjectLeaders) Then
ProjectLeader = "[ProjectLeaderID] like '*'"
Else
ProjectLeader = "[ProjectLeaderID] = " & Me.cbo_ProjectLeaders
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" & Protocol & "And" & SampleProvider & "And" & BRL & "And" & ProjectLeader & "And" _
& ExecutionDate & "And" & Extern & "And" & Intern & "And" & Classification & "And" _
& SampleProvider2 & "And" & Material & "And" & strText
task = "Select * from qry_Administration where (" & strCriteria & ") order by ExecutionDate DESC"
Debug.Print (task)
Me.Form.RecordSource = task
Me.Form.Requery
End Function
Part of query with solution:
If IsNull(Me.cbo_CustomerLocations) Then
CustomerLocation = "[CustomerLocationID] like '*'"
Else
CustomerLocation = "[LocationCompanyName] = '" & Me.cbo_CustomerLocations.Column(0) & "'"
CustomerLocationPlace = "[LocationCompanyPlace] = '" & Me.cbo_CustomerLocations.Column(1) & "'"
End If
And for the adjustsments on strCriteria:
strCriteria = Customer & "And" & CustomerLocation & "And" & CustomerLocationPlace & .........

Vba in access. Filtering query

I am having a issue with vba in access. I wrote a code to filter a form and generate a report via button. Now when I run the query , it will only filter and generate the report if I put the report on the same page as the form. Is there a way to make it so that my report will be created seperately?
Private Sub Search_Click()
Dim strWhere As String
Dim i As Variant
Dim varItem As Variant
Dim strDelim As String
If Nz(Me.txtFullName, "") <> "" Then
strWhere = strWhere & "FullName Like '*" & Replace(Me.txtFullName, "'", "''") & "*' AND "
End If
If Nz(Me.txtCivil, "") <> "" Then
strWhere = strWhere & "CivilService_Status Like '*" & Replace(Me.txtCivil, "'", "''") & "*' AND "
End If
If Nz(Me.txtOffice, "") <> "" Then
strWhere = strWhere & "Office_Title Like '*" & Replace(Me.txtOffice, "'", "''") & "*' AND "
End If
If Nz(Me.cboPosition, "") <> "" Then
strWhere = strWhere & "[Full Time],[Part Time] = '" & Me.cboPosition.Value & "' AND "
End If
If Nz(Me.txtStartdate, "") <> "" Then
strWhere = strWhere & "AgencyStart_Date Like '*" & Replace(Me.txtStartdate, "'", "''") & "*' AND "
End If
For Each i In Me.lstBureau.ItemsSelected 'listbox
If Nz(Me.txtdivision, "") <> "" Then
strWhere = strWhere & "Division Like '*" & Replace(Me.txtdivision, "'", "''") & "*' AND "
End If
Next i
If strWhere <> "" Then
strWhere = Left(strWhere, Len(strWhere) - 5)
Report_Onboard_summary.Filter = strWhere
Report_Onboard_summary.FilterOn = True
'DoCmd.OpenReport "Onboard_summary", acViewReport, strWhere
Else
Report_Onboard_summary.Filter = ""
Report_Onboard_summary.FilterOn = False
End If
End Sub
Any help would be greatly appreciated
I usually open reports with the OpenReport command.
DoCmd.OpenReport "Report_Onboard_summary", acViewPreview, WhereCondition:=strWhere
for previewing, or
DoCmd.OpenReport "Report_Onboard_summary", acViewNormal, WhereCondition:=strWhere
for immediate printing.
This assumes that the report is created as a Report object stored separately in the database, not a Form object. You said that you stored it on the same page, this leads me to believe that you have a sub-Form and not an actual Report.

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.

Add Error "3134" Syntax error in INSERT INTO statement - Update and Delete error '3061' Too few parameters

I have limited experience with Access. I followed some YouTube tutorials and made a functioning DB a couple of months ago.
I adapted the first DB, which essentially is changing the field names in the table in the Access file.
I can't get the new DB to function. I have a form with a subtable of the main table and it has a few text fields to fill in with the information to input. Then it has a few buttons to the side that either Add to the table, Delete from the table, Clear the text fields, Close the form, Edit a selected field, and then the Add button changes to Update after you Edit a field so that you can click Update to update the selected field after you've made changes to it.
All of this works in my first DB and in theory it should work exactly the same after changing the field names in the new DB and the corresponding txt field names and so on. I am having a tough time getting it to work for Add, Update, or Delete.
The error on the Add is Run time error "3134" Syntax error in INSERT INTO statement.
The Update and Delete error is run time error '3061' Too few parameters. expected 1.
The Clear works, as well as the Close and Edit.
Here is the code:
Option Compare Database
Private Sub cmdAdd_Click()
'when we click on button Add there are two options
'1. for insert
'2. for update
If Me.txtICN.Tag & "" = "" Then
'this is for insert new
'add data to table
CurrentDb.Execute "INSERT INTO tblInventory(ICN, manu, modelNum, serialNum, descr, dateRec, projectNum, dispo, flgDispo, dateRemoved, comments)" & _
" VALUES(" & Me.txtICN & ", '" & Me.txtManu & "', '" & Me.txtModel & "', '" & Me.txtSerial & "', '" & Me.txtDescrip & "', '" & Me.txtDateRec & "', '" & Me.txtProjectNum & "', '" & Me.txtDispo & "', '" & Me.chkFlag & "', '" & Me.txtDateRemoved & "', '" & Me.txtComments & "')"
Else
'otherwise (Tag of txtICN store the Lab Inventory Control Number to be modified)
CurrentDb.Execute "UPDATE tblInventory " & _
" SET ICN = " & Me.txtICN & _
", manu = '" & Me.txtManu & "'" & _
", modelNum = '" & Me.txtModel & "'" & _
", serialNum = '" & Me.txtSerial & "'" & _
", descr = '" & Me.txtDescrip & "'" & _
", dateRec = '" & Me.txtDateRec & "'" & _
", projectNum = '" & Me.txtProjectNum & "'" & _
", dispo = '" & Me.txtDispo & "'" & _
", flgDispo = '" & Me.chkFlag & "'" & _
", dateRemoved = '" & Me.txtDateRemoved & "'" & _
", comments = '" & Me.txtComments & "'" & _
" WHERE ICN = " & Me.txtICN.Tag
End If
'clear form
cmdClear_Click
'refresh data in list on form
tblInventorySub.Form.Requery
End Sub
Private Sub cmdClear_Click()
Me.txtICN = ""
Me.txtManu = ""
Me.txtModel = ""
Me.txtSerial = ""
Me.txtDescrip = ""
Me.txtDateRec = ""
Me.txtProjectNum = ""
Me.txtDispo = ""
Me.chkFlag = ""
Me.txtDateRemoved = ""
Me.txtComments = ""
'focus on ICN text box
Me.txtICN.SetFocus
'set button edit to enable
Me.cmdEdit.Enabled = True
'change caption of button add to Add
Me.cmdAdd.Caption = "Add"
'clear tag on txtICN for reset new
Me.txtICN.Tag = ""
End Sub
Private Sub cmdClose_Click()
DoCmd.Close
End Sub
Private Sub cmdDelete_Click()
'delete record
'check existing selected record
If Not (Me.tblInventorySub.Form.Recordset.EOF And Me.tblInventorySub.Form.Recordset.BOF) Then
'confirm delete
If MsgBox("Are you sure you want to delete this inventory entry?", vbYesNo) = vbYes Then
'delete now
CurrentDb.Execute "DELETE FROM tblInventory " & _
"WHERE ICN = " & Me.tblInventorySub.Form.Recordset.Fields("ICN")
'refresh data in list
Me.tblInventorySub.Form.Requery
End If
End If
End Sub
Private Sub cmdEdit_Click()
'check whether there exists data in list
If Not (Me.tblInventorySub.Form.Recordset.EOF And Me.tblInventorySub.Form.Recordset.BOF) Then
'get data to text box control
With Me.tblInventorySub.Form.Recordset
Me.txtICN = .Fields("ICN")
Me.txtManu = .Fields("manu")
Me.txtModel = .Fields("modelNum")
Me.txtSerial = .Fields("serialNum")
Me.txtDescrip = .Fields("descr")
Me.txtDateRec = .Fields("dateRec")
Me.txtProjectNum = .Fields("projectNum")
Me.txtDispo = .Fields("dispo")
Me.chkFlag = .Fields("flgDispo")
Me.txtDateRemoved = .Fields("dateRemoved")
Me.txtComments = .Fields("comments")
'store ICN in Tag of txtICN in case id is modified
Me.txtICN.Tag = .Fields("ICN")
'change caption of button add to Update
Me.cmdAdd.Caption = "Update"
'disable button edit
Me.cmdEdit.Enabled = False
End With
End If
End Sub
What data types are dateRec, flgDispo, dateRemoved? Values for DateTime fields must be delimited with # not '. Is flgDispo a Yes/No type? If so, this is numeric type field and number values do not have delimiters.
Why delete records? Do you really want to lose history? Why not just flag as 'Archived' or 'Inactive'? Deleting records should be a rare event.
I always give subform containers a name different from the object they hold, like ctrInventory:
CurrentDb.Execute "DELETE FROM tblInventory WHERE ICN = " & Me.ctrInventory!ICN
First, all your date expressions must be formatted like this:
", dateRec = #" & Format(Me.txtDateRec.Value, "yyyy\/mm\/dd") & "#" & _
or you could apply my CSql function to handle all this:
Convert a value of any type to its string representation
However, it appears that you could make life much easier for yourself by simply binding your form to the table - and then remove all of this code as the form will handle edit, insert, and delete automatically.