Ms-Access how to use a query with a parameter inside a form - sql

I have an SQL query with a question(alert like) that pops up every time I open it...
For every value inserted in that question you get diffrent result.
I Want to be able to use that query in my form with a combo-box...
I don't know how to exceute the query with the parameter from within the form....
I have no problem using VBA, just tell me how to call the query with the parameter
Thanks,
Fingerman

I usually use my filtering forms using the following principles:
1) I first create a query that includes all the fields I want to display and all the fields I want to filter on. It can use more than one table. I do not set any criteria (WHERE clause) in this query unless there is a condition that always needs to be applied no matter what.
2) Next I create a datasheet form based on this query and I save it, giving it a name that indicates that it's a subform.
3) Next I create an unbound main form and add unbound controls such as textboxes, combos, listboxes, checkboxes, etc. that will be used to filter the different fields. One control can potentially allow a user to search on more than one field depending how you write your filtering routine in VBA.
4) Now it's time to write code on the main form to make this all work. Basically, the code needs to check to see if there are values in any of the controls and if so, it creates a WHERE clause (without the WHERE keyword) and at the very end it sets the subform's filter property and turns the subform's FilterOn property to TRUE.
Here's some example code. This was taken from the sample database I've made just to demonstrate filtering (see below). This example does not use fuzzy searches (asterisks) and each control on the main form only filters one field on the subform.
Private Sub cmdFilter_Click()
'You can also call the FilterSubForm function on a control's AfterUpdate event.
Call FilterSubform
End Sub
Private Sub FilterSubform()
Dim strFilter As String
'Note: We have to wrap field names in brackets if they contain spaces or
'special characters. These fields are in Northwind Traders 2007 from Microsoft
'I would never consider naming my fields with spaces or special characters
'in them.
'Company
If Nz(Me.txtCompany, "") <> "" Then
strFilter = strFilter & "Company = '" & PQ(Me.txtCompany) & "' And "
End If
'First Name
If Nz(Me.txtFirstName, "") <> "" Then
strFilter = strFilter & "[First Name] = '" & PQ(Me.txtFirstName) & "' AND "
End If
'Last Name
If Nz(Me.txtLastName, "") <> "" Then
strFilter = strFilter & "[Last Name] = '" & PQ(Me.txtLastName) & "' AND "
End If
'Business Phone
If Nz(Me.txtBusinessPhone, "") <> "" Then
strFilter = strFilter & "[Business Phone] = '" & PQ(Me.txtBusinessPhone) & "' AND "
End If
'City
If Nz(Me.cboCity, "") <> "" Then
strFilter = strFilter & "City = '" & PQ(Me.cboCity) & "' AND "
End If
'State/Province
If Nz(Me.cboStateProvince, "") <> "" Then
strFilter = strFilter & "[State/Province] = '" & PQ(Me.cboStateProvince) & "' AND "
End If
'Order Date
If Nz(Me.txtOrderDate, "") <> "" Then
If IsDate(Me.txtOrderDate) = True Then
strFilter = strFilter & "[Order Date] = #" & Me.txtOrderDate & "# AND "
End If
End If
'Ship Name
If Nz(Me.txtShipName, "") <> "" Then
strFilter = strFilter & "[Ship Name] = '" & PQ(Me.txtShipName) & "' AND "
End If
'Ship City
If Nz(Me.txtShipCity, "") <> "" Then
strFilter = strFilter & "[Ship City] = '" & PQ(Me.txtShipCity) & "' AND "
End If
'Ship State/Province
If Nz(Me.cboShipStateProvince, "") <> "" Then
strFilter = strFilter & "[Ship State/Province] = '" & PQ(Me.cboShipStateProvince) & "' AND "
End If
'Product Code
If Nz(Me.cboProductCode, "") <> "" Then
strFilter = strFilter & "[Product Code] = '" & PQ(Me.cboProductCode) & "' AND "
End If
'Quantity
If Nz(Me.txtQuantity, "") <> "" Then
If IsNumeric(Me.txtQuantity) = True Then
strFilter = strFilter & "Quantity = " & Me.txtQuantity & " AND "
End If
End If
If Right(strFilter, 5) = " AND " Then strFilter = Left(strFilter, Len(strFilter) - 5)
If strFilter <> "" Then
Me.subformOrderSearch.Form.Filter = strFilter
Me.subformOrderSearch.Form.FilterOn = True
Else
'Clear the filter
Me.subformOrderSearch.Form.Filter = ""
Me.subformOrderSearch.Form.FilterOn = False
End If
End Sub
Private Function PQ(s As String) As String
'This function is used to "pad quotes" for SQL
PQ = Replace(s, "'", "''")
End Function
I've put together a sample database that has several different examples all building on what I've posted here. You can download this database here:
http://www.utteraccess.com/forum/Search-filtering-Examples-t1968063.html

After some Searching, I have came across this:
http://www.techrepublic.com/blog/msoffice/run-a-parameter-query-within-an-access-form/701
It is not what I wanted, But it is a great solution...
I will wait, if no one gets a better answer, I'll accept my own (As much as I hate doing that).

Related

Recordset Not Updating Table with Changed and/or Correct Values

The codes purpose is to 'build' the correct name style for each record in a CDSal and FormatName field. I have a group of tables (all linked) with individuals Full Name(NewName), Salutation, First, Middle and Last Name, as well as Client defaults for what to do with those names (!NewName, !First, !AA, etc.).
The Recordset is pulled from a query in the database that brings some necessary fields together from 2 different tables. From Access I can open the query, make any changes needed to any of the fields, save the record and see the changes reflected in the underlying tables. When I run the following code, the Debug.Print's produce the expected outcomes but nothing is permanently saved to the tables. The code never errors (which might be part of the problem) and for Case "!AA" both CDSal and FormatName fields are filled with !NewName when Debug.Print again shows the expected outcome. Case "!AA" is the only instance where anything is actually changed on the tables.
I have attempted everything that I could find on the Internet to troubleshoot this error as well as multiple different configurations to get something to "stick". Hopefully it is a simple answer, let me know what you all think.
Private Sub Form_Load()
On Error GoTo Form_Load_Err
'_ SetUp Variables _'
Dim strQry As String, strSQL As String, strName As String
Dim rstName As DAO.Recordset
'_ Declare Variables _'
strQry = "MyQueryName"
Set rstName = CurrentDb.OpenRecordset(strQry, dbOpenDynaset)
'_ Begin Code _'
With rstName
If Not (.EOF And .BOF) Then .MoveFirst
Do Until .EOF = True
'Update CDSal with correct Naming Information
Debug.Print !NewName
.Edit
Select Case !CDSal_Client
Case "NewName" 'Clients that use NewName for blah
!CDSal = !NewName
Case "First" 'Clients that use First for blah
!CDSal = !First
Case "AA" 'ClientName: CDSal = First, FormatName = NewName(w/o Sal)
!CDSal = !First
If !Sal <> "" Then
!FormatName = !First & " " & !Middle & " " & !Last
Else
!FormatName = !NewName
End If
Case "BB" 'ClientName: Client uses specific breakdown for names
If !Sal <> "" And !Last <> "" Then
!CDSal = !Sal & " " & !Last
!FormatName = !Sal & " " & !Last
ElseIf !First <> "" And !Last <> "" Then
!CDSal = !First & " " & !Last
!FormatName = !First & " " & !Last
ElseIf !First <> "" Then
!CDSal = !First
!FormatName = !First
Else
!CDSal = "Valued Member"
!FormatName = "Valued Member"
End If
Case "CC" 'ClientName: CDSal = NewName(trim " & " if needed) = NewName + AddlName(done on import)
If Right(!NewName, 3) = " & " Then
Replace !NewName, " & ", ""
!CDSal = !NewName
Else
!CDSal = !NewName
End If
End Select
.Update
Debug.Print !CDSal
Debug.Print !FormatName
.MoveNext
Loop
'Removes additional spaces left over from concatenating fields
strSQL = "UPDATE [" & strQry & "] SET [FormatName] = REPLACE(REPLACE(REPLACE([FormatName],' ','<>'),'><',''),'<>',' '), " & _
"[CDSal] = REPLACE(REPLACE(REPLACE([FormatName],' ','<>'),'><',''),'<>',' ');"
CurrentDb.Execute strSQL
End With
'_ Error Handling & CleanUp
Form_Load_ClnUp:
rstName.Close
Set rstName = Nothing
Exit Sub
Form_Load_Err:
MsgBox Err.SOURCE & " : " & Err.Number & vbCr & _
"Error Description : " & Err.Description
GoTo Form_Load_ClnUp
End Sub
MyQueryName SQL
SELECT T_Individual.ID_IndivRecords, T_Individual.NewName, T_Individual.NewName2, T_Individual.CDSal, T_Individual.FormatName, T_Individual.Status_, T_Individual.Sal, T_Individual.First, T_Individual.Middle, T_Individual.Last, T_Clients.ID_Client, T_Clients.CDSal_Client, T_Individual.Date
FROM T_Individual INNER JOIN (T_Clients INNER JOIN (T_Jobs INNER JOIN T_IndivJobs ON T_Jobs.ID_Jobs = T_Individual.Jobs) ON T_Clients.ID_Client = T_Jobs.Client) ON T_Individual.ID_IndivRecords = T_IndivJobs.ID_DonorRecords
WHERE (((T_Individual.Date)=Date()));
strSQL = "UPDATE [" & strQry & "] SET [FormatName] = REPLACE(REPLACE(REPLACE([FormatName],' ','<>'),'><',''),'<>',' '), " & _
"[CDSal] = REPLACE(REPLACE(REPLACE([FormatName],' ','<>'),'><',''),'<>',' ');"
Another instance of a simple error and or mistype can drastically affect everything you are trying to achieve. This SQL was ran after the code was processed to remove any double spaces that might have been in the original data or created from concatenation. Notice that the CDSal field will be replaced with the FormatName field in the last line instead of being replaced with itself. Since most records do not use the FormatName field their CDSal field was getting replaced with NULL . . .
I have corrected this issue and everything runs very smoothly and correctly now.
Thanks for everyone who tried to help on this! Any additional information on Formatting or Optimization is always appreciated.

Search button using more than one text field Access vba

This is my code below. I am trying to search a database using two different dates, company name
I am getting an error when one of the date fields is empty or null. How can I solve this issue or bypass if the date search field is empty to ignore it in the search or search for an empty field?
Dim SQL As String
SQL = "SELECT * from qryRequestInternal where ([DateRequestSent] = #" & txt_Search_Sdate & "# AND [DateReceived] = #" & txt_Search_Rdate & "# AND (companyName like ""*" & txt_SCompNa & "*"") )"
Me.sfrmRequestInternal.Form.RecordSource = SQL
Me.sfrmRequestInternal.Form.Requery
Me.sfrmRequestInternal_col.Form.RecordSource = SQL
Me.sfrmRequestInternal_col.Form.Requery
End Sub
You will need to check for Null values and build the SQL string based on the controls which have a value (i.e. not null).
The example below uses a helper function to build the sql string. If nothing is inserted, it will only run the the Select * from qryRequestInternal without any criteria.
Private Function SqlWhere() As String
Dim retvalue As String
'sent date
With txt_Search_Sdate
If Not IsNull(.Value) Then
retvalue = " WHERE [DateRequestSent] = #" & Format(.Value, "mm/dd/yyyy") & "#"
End If
End With
'received date
With txt_Search_Rdate
If Not IsNull(.Value) Then
retvalue = IIf(Len(retvalue) = 0, " WHERE", retvalue & " AND") & " [DateReceived] = #" & Format(.Value, "mm/dd/yyyy") & "#"
End If
End With
'company
With txt_SCompNa
If Not IsNull(.Value) Then
retvalue = IIf(Len(retvalue) = 0, " WHERE", retvalue & " AND") & " [companyName] Like '*" & .Value & "*'"
End If
End With
SqlWhere = retvalue
End Function
To call it:
Dim sqlString As String
sqlString = "SELECT * from qryRequestInternal" & SqlWhere()
Debug.Print sqlString

Using keywords to find records and list them in a listbox

I have a form (frmSearch) that I use several (4) comboboxes to filter out results for a listbox (lstCustomers). What I'm attempting to do now is create the ability to filter the listbox based on a text box of "keywords". Additionally, the column which the keyword box will search will be variable based on cboWhere which is a list of columns from tblContacts (the table qryContactWants uses)
I found a really nice Function set with the following code that will let me filter everything, but I'm not entirely sure how to turn this data around and use it to filter out my listbox.
This function organizes the keywords:
Public Function FindAnyWord(varFindIn, strWordList As String) As Boolean
Dim var
Dim aWords
aWords = Split(strWordList, ",")
For Each var In aWords
If FindWord(varFindIn, var) Then
FindAnyWord = True
Exit Function
End If
Next var
End Function
And this function actually performs the search:
Public Function FindWord(varFindIn As Variant, varWord As Variant) As Boolean
Const PUNCLIST = """' .,?!:;(){}[]-—/"
Dim intPos As Integer
FindWord = False
If Not IsNull(varFindIn) And Not IsNull(varWord) Then
intPos = InStr(varFindIn, varWord)
' loop until no instances of sought substring found
Do While intPos > 0
' is it at start of string
If intPos = 1 Then
' is it whole string?
If Len(varFindIn) = Len(varWord) Then
FindWord = True
Exit Function
' is it followed by a space or punctuation mark?
ElseIf InStr(PUNCLIST, Mid(varFindIn, intPos + Len(varWord), 1)) > 0 Then
FindWord = True
Exit Function
End If
Else
' is it precedeed by a space or punctuation mark?
If InStr(PUNCLIST, Mid(varFindIn, intPos - 1, 1)) > 0 Then
' is it at end of string or followed by a space or punctuation mark?
If InStr(PUNCLIST, Mid(varFindIn, intPos + Len(varWord), 1)) > 0 Then
FindWord = True
Exit Function
End If
End If
End If
' remove characters up to end of first instance
' of sought substring before looping
varFindIn = Mid(varFindIn, intPos + 1)
intPos = InStr(varFindIn, varWord)
Loop
End If
End Function
And here is the code that I typically use to filter the listbox using the comboboxes on frmSearch:
Dim column As String
SQL = "SELECT qryContactWants.ID, qryContactWants.FullName, qryContactWants.Type, qryContactWants.Make, qryContactWants.Model, qryContactWants.YearWanted, qryContactWants.Condition " _
& "FROM qryContactWants " _
& "WHERE 1=1 "
If cboType.Value & "" <> "" Then
SQL = SQL & " AND qryContactWants.Type = '" & cboType.Value & "'"
End If
If cboMake.Value & "" <> "" Then
SQL = SQL & " AND qryContactWants.Make = '" & cboMake.Value & "'"
End If
If cboModel.Value & "" <> "" Then
SQL = SQL & " AND qryContactWants.Model = '" & cboModel.Value & "'"
End If
If cboYear.Value & "" <> "" Then
SQL = SQL & " AND qryContactWants.YearWanted = '" & cboYear.Value & "'"
End If
If cboCondition.Value & "" <> "" Then
SQL = SQL & " AND qryContactWants.Condition = '" & cboCondition.Value & "'"
End If
SQL = SQL & " ORDER BY qryContactWants.Last"
Me.lstCustomers.RowSource = SQL
Me.lstCustomers.Requery
End Sub
What I would like to do is take the functions I found for searching keywords and apply it to my form and aid in returning a list of customers in lstCustomers
Ideally, having the keyword function return an SQL statement similar to those I'm using to filter out the listbox would be perfect. This would allow me to add a simple SQL = SQL & "AND qryContactWants.VARIABLECOLUMNHERE =SOMETHING
EDIT 1:
While using the following code, VBA is tossing a compile error on the second "End If" stating there isn't a Block If. There clearly is, so I'm not sure what's going on. Here is the code I'm using:
Public Function KeyWhere(strKeys As String, strColumn As String) As String
Dim b As Variant
strKeys = Replace(strKeys, vbCrLf, ",") ' remove all line returns
b = Split(strKeys, ",")
Dim strWhere As String
Dim v As Variant
For Each v In b
If Trim(b) <> "" Then
If strWhere <> "" Then strWhere = strWhere & " or "
strWhere = strWhere & strColumn & " like '*" & Trim(v) & "*'"
End If
End If
Next
strWhere = "(" & strWhere & ")"
KeyWhere = strWhere
End Function
And under the function RequerylistCustomers() I added the If IsNull (Me.txtSearch) = False Then code below:
Private Sub RequerylstCustomers()
Dim SQL As String
'Dim criteria As String
Dim column As String
SQL = "SELECT qryContactWants.ID, qryContactWants.FullName, qryContactWants.Type, qryContactWants.Make, qryContactWants.Model, qryContactWants.YearWanted, qryContactWants.Condition " _
& "FROM qryContactWants " _
& "WHERE 1=1 "
If cboType.Value & "" <> "" Then
SQL = SQL & " AND qryContactWants.Type = '" & cboType.Value & "'"
End If
If cboMake.Value & "" <> "" Then
SQL = SQL & " AND qryContactWants.Make = '" & cboMake.Value & "'"
End If
If cboModel.Value & "" <> "" Then
SQL = SQL & " AND qryContactWants.Model = '" & cboModel.Value & "'"
End If
If cboYear.Value & "" <> "" Then
SQL = SQL & " AND qryContactWants.YearWanted = '" & cboYear.Value & "'"
End If
If cboCondition.Value & "" <> "" Then
SQL = SQL & " AND qryContactWants.Condition = '" & cboCondition.Value & "'"
End If
Dim strWhere As String
'Grab Keywords from txtSearch using cboWhere to search for those keywords
If IsNull(Me.txtSearch) = False Then
strWhere = KeyWhere(Me.txtSearch, Me.cboWhere)
SQL = SQL & " AND " & strWhere
End If
SQL = SQL & " ORDER BY qryContactWants.Last"
Me.lstCustomers.RowSource = SQL
Me.lstCustomers.Requery
End Sub
Are the keywords to be searched in a single column (say a comments or memo column?). If yes, then you should be able to optional "add" the one additional criteria to your current "set" of combo box filters.
Are we to assume that the keywords can appear anywhere in that memo column to search?
So, if there are "key words entered into that text box, then you call KeyWhere.
eg this routine:
Public Function KeyWhere(strKeys As String, strColumn As String) As String
Dim b As Variant
strKeys = Replace(strKeys, vbCrLf, ",") ' remove all line returns
b = Split(strKeys, ",")
Dim strWhere As String
Dim v As Variant
For Each v In b
if trim(v) <> "" then
If strWhere <> "" Then strWhere = strWhere & " or "
strWhere = strWhere & strColumn & " like '*" & Trim(v) & "*'"
end if
Next
strWhere = "(" & strWhere & ")"
KeyWhere = strWhere
End Function
We assume each key word is separated by a comma (could be space, but comma is better).
So, if I type in the following command in debug window to test the above?
? keywhere("Generator, Water maker, Battery","Notes")
OutPut:
(Notes like '*Generator*' or Notes like '*Water maker*' or Notes like '*Battery*')
So, we just append the above results to your final SQL.
eg:
dim strWhere as string
if isnull(me.KeyWordBox) = False then
strWhere = keyWhere(me.KeyWordBox,me.cboColumnToSearch)
SQL = SQL & " AND " & strWhere
end if
so, the above converts all keywords into a valid SQL condition for the column to search. It is likely that column is some kind of notes column, but it would work for other description type field to search.

MS Access filter form to open report to specific records

I'm trying to create a form, ReportSearch that has multiple comboboxes and textboxes that will allow the user to narrow down the results shown on the report. Not all fields would have to be used in the search.
On click the following code will ask for the parameter value to be entered for the specific IDs used. If I just click OK without entering anything in the MsgBox the report will be opened with no records.
Private Sub cmdFilter_Click()
Dim strWhere As String
Dim lngLen As Long
Const conJetDate = "\#mm\/dd\/yy\#"
If Not IsNull(Me.cboSearchJob) Then
strWhere = strWhere & "(Job.id = " & Me.cboSearchJob & ") AND "
End If
If Not IsNull(Me.cboSearchEmployee) Then
strWhere = strWhere & "(Employee.ID = " & Me.cboSearchEmployee & ") AND "
End If
If Not IsNull(Me.cboSearchService) Then
strWhere = strWhere & "(Service.ID = " & Me.cboSearchService & ") AND "
End If
If Not IsNull(Me.tboStartDate) Then
strWhere = strWhere & "(DateWorked >= " & Format(Me.tboStartDate, conJetDate) & ") AND "
End If
If Not IsNull(Me.tboEndDate) Then
strWhere = strWhere & "(DateWorked < " & Format(Me.tboEndDate + 1, conJetDate) & ") AND "
End If
lngLen = Len(strWhere) - 5
If lngLen <= 0 Then
MsgBox "No Results", vbInformation, "No Search Available."
Else
strWhere = Left$(strWhere, lngLen)
DoCmd.OpenReport "JobReport", acViewPreview
Reports!JobReport.Filter = strWhere
Reports!JobReport.FilterOn = True
End If
End Sub
For the report I'm using
SELECT [Employees].[FirstName] & " " & [Employees].[LastName] AS EmployeeName, Jobs.JobName, Equipment.Model, Service.Service, Labor.Labor, EmployeeWorkLog.LaborHours, EmployeeWorkLog.EquipmentHours, EmployeeWorkLog.Notes, EmployeeWorkLog.DateWorked, Service.ID
FROM Service RIGHT JOIN (Labor RIGHT JOIN (Jobs RIGHT JOIN (Equipment RIGHT JOIN (Employees RIGHT JOIN EmployeeWorkLog ON Employees.ID = EmployeeWorkLog.EmployeeID) ON Equipment.ID = EmployeeWorkLog.EquipmentID) ON Jobs.ID = EmployeeWorkLog.JobID) ON Labor.ID = EmployeeWorkLog.LaborID) ON Service.ID = EmployeeWorkLog.ServiceID
ORDER BY [Employees].[FirstName] & " " & [Employees].[LastName];
At this point I'm at a complete loss.
Obviously there is something that I'm missing here. Let me know in what way I need to modify this code to get it to open my report JobReport filtered based on my form ReportSearch.
Thanks.
A report isn't dynamic like a form, you can't filter it after it has been opened. When a report is opened in print preview, it reads its data, does the layout and formatting, then it's completely static.
To open a report with filtered data, use the WhereCondition parameter of DoCmd.OpenReport:
DoCmd.OpenReport "JobReport", acViewPreview, WhereCondition:=strWhere

Access 2007 VBA & SQL - Update a Subform pointed at a dynamically created query

Abstract:
I'm using VB to recreate a query each time a user selects one of 3 options from a drop down menu, which appends the WHERE clause If they've selected anything from the combo boxes. I then am attempting to get the information displayed on the form to refresh thereby filtering what is displayed in the table based on user input.
1) Dynamically created query using VB.
Private Sub BuildQuery()
' This sub routine will redefine the subQryAllJobsQuery based on input from
' the user on the Management tab.
Dim strQryName As String
Dim strSql As String ' Main SQL SELECT statement
Dim strWhere As String ' Optional WHERE clause
Dim qryDef As DAO.QueryDef
Dim dbs As DAO.Database
strQryName = "qryAllOpenJobs"
strSql = "SELECT * FROM tblOpenJobs"
Set dbs = CurrentDb
' In case the query already exists we should deleted it
' so that we can rebuild it. The ObjectExists() function
' calls a public function in GlobalVariables module.
If ObjectExists("Query", strQryName) Then
DoCmd.DeleteObject acQuery, strQryName
End If
' Check to see if anything was selected from the Shift
' Drop down menu. If so, begin the where clause.
If Not IsNull(Me.cboShift.Value) Then
strWhere = "WHERE tblOpenJobs.[Shift] = '" & Me.cboShift.Value & "'"
End If
' Check to see if anything was selected from the Department
' drop down menu. If so, append or begin the where clause.
If Not IsNull(Me.cboDepartment.Value) Then
If IsNull(strWhere) Then
strWhere = strWhere & " AND tblOpenJobs.[Department] = '" & Me.cboDepartment.Value & "'"
Else
strWhere = "WHERE tblOpenJobs.[Department] = '" & Me.cboDepartment.Value & "'"
End If
End If
' Check to see if anything was selected from the Date
' field. If so, append or begin the Where clause.
If Not IsNull(Me.txtDate.Value) Then
If Not IsNull(strWhere) Then
strWhere = strWhere & " AND tblOpenJobs.[Date] = '" & Me.txtDate.Value & "'"
Else
strWhere = "WHERE tblOpenJobs.[Date] = '" & Me.txtDate.Value & "'"
End If
End If
' Concatenate the Select and the Where clause together
' unless all three parameters are null, in which case return
' just the plain select statement.
If IsNull(Me.cboShift.Value) And IsNull(Me.cboDepartment.Value) And IsNull(Me.txtDate.Value) Then
Set qryDef = dbs.CreateQueryDef(strQryName, strSql)
Else
strSql = strSql & " " & strWhere
Set qryDef = dbs.CreateQueryDef(strQryName, strSql)
End If
End Sub
2) Main Form where the user selects items from combo boxes.
picture of the main form and sub form
http://i48.tinypic.com/25pjw2a.png
3) Subform pointed at the query created in step 1.
Chain of events:
1) User selects item from drop down list on the main form.
2) Old query is deleted, new query is generated (same name).
3) Subform pointed at query does not update, but if you open the query by itself the correct results are displayed.
Name of the Query: qryAllOpenJobs
name of the subform: subQryAllOpenJobs
Also, the Row Source of subQryAllOpenJobs = qryAllOpenJobs
Name of the main form: frmManagement
I think you have your logic on the Department drop down check backwards.
You have it checking if strWhere is null, then if it is, you concatenate strWhere with the value of cboDepartment.
You should be doing what you are for Date.
' Check to see if anything was selected from the Department
' drop down menu. If so, append or begin the where clause.
If Not IsNull(Me.cboDepartment.Value) Then
If Not IsNull(strWhere) Then
strWhere = strWhere & " AND tblOpenJobs.[Department] = '" & Me.cboDepartment.Value & "'"
Else
strWhere = "WHERE tblOpenJobs.[Department] = '" & Me.cboDepartment.Value & "'"
End If
End If
You may also want to do:
If Nz(strWhere,"") = "" then
Instead of just doing IsNull so that you catch the zero-length string in addition to a null variable.
As for setting the recordsource, use something along the lines of
Me.sfrmJobs.Form.RecordSource = strSQL
where sfrmJobs is the name of your subform.
An empty string is not the same thing as Null. When you declare a String variable such as this:
Dim strWhere As String
strWhere is initialized as an empty string (or "zero length string"). That value is sometimes referred to as a null string, and there is even a VBA constant, vbNullString, which represents the empty string. However, regardless of which name you use, the empty string variable is not Null. Furthermore a VBA String variable can never be Null. For example, this code will cause error 94, 'Invalid use of Null':
Dim strWhere As String
strWhere = Null
The reason I am emphasizing this point is because your code tests whether strWhere is Null. That is a logic flaw because strWhere will never be Null. For example, I don't believe this condition can ever be True:
If IsNull(strWhere) Then
If you want a test to determine when strWhere has not had a value assigned to it (it's still an empty string), use the Len function:
If Len(strWhere) = 0 Then
Here is a different approach for BuildQuery. It assumes the data type for your [Date] field is String (as your original code suggests). If [Date] is actually Date/Time data type, this code will not work. Also, please note that Date is a reserved word (see Problem names and reserved words in Access). I enclosed the field name in square brackets to avoid ambiguity. If it were my own database, I would change the field name instead.
Private Sub BuildQuery()
'* Update subform RecordSource based on input from *'
'* the user on the Management tab. *'
Dim strSql As String ' Main SQL SELECT statement '
Dim strWhere As String ' Optional WHERE clause '
Dim i As Integer
Dim strControl As String
Dim strField As String
strSql = "SELECT * FROM tblOpenJobs AS oj"
strWhere = vbNullString
For i = 1 To 3
Select Case i
Case 1
strControl = "cboShift"
strField = "Shift"
Case 2
strControl = "cboDepartment"
strField = "Department"
Case 3
strControl = "txtDate"
strField = "[Date]"
End Select
If Not IsNull(Me.Controls(strControl).Value) Then
strWhere = strWhere & _
IIf(Len(strWhere) > 0, " AND ", "") & _
"oj." & strField & " = '" & _
Me.Controls(strControl).Value & "'"
End If
Next i
If Len(strWhere) > 0 Then
strSql = strSql & " WHERE " & strWhere
End If
'* use the name of the subform CONTROL for sfrmJobs *'
'* (may not be the name of the subform) *'
Me.sfrmJobs.Form.RecordSource = strSql
End Sub
My solution is below in three parts. (1) Build Query, (2) Main Form, (3) Subform.
`Private Sub OpenJobsQuery()
' This sub will construct the query on the front page for the user
' based on who they are and what they select from the combo boxes above
' the table for filtering by redefining the rowsource of the subform
' subQryOpenJobs
Dim strSql As String ' Main SQL SELECT statement
Dim strWhere As String ' Where clause containing user specified parameters.
strSql = "SELECT * FROM tblOpenJobs"
strWhere = ""
' Check to see if anything was selected from the Shift
' combo box. If so, begin the Where clause.
If Not IsNull(Me.cboOpenJobShift.Value) Then
strWhere = "WHERE tblOpenJobs.[Shift] = '" & Me.cboOpenJobShift.Value & "'"
End If
' Check to see if anything was selected from the Department
' combo box. If so, append or begin the where clause.
If Not IsNull(Me.cboOpenJobDepartment.Value) Then
If strWhere = "" Then
strWhere = "WHERE tblOpenJobs.[Department] = '" & Me.cboOpenJobDepartment.Value & "'"
Else
strWhere = strWhere & " AND tblOpenJobs.[Department] = '" & Me.cboOpenJobDepartment.Value & "'"
End If
End If
' Check to see if anything was selected from the Date
' field. If so, append or begin the Where clause.
If Not IsNull(Me.cboOpenJobDate.Value) Then
If strWhere = "" Then
strWhere = "WHERE tblOpenJobs.[JobDate] = #" & Me.cboOpenJobDate.Value & "#"
Else
strWhere = strWhere & " AND tblOpenJobs.[JobDate] = #" & Me.cboOpenJobDate.Value & "#"
End If
Else
' If nothing was entered in the date field, make sure the user
' only sees future jobs.
If strWhere = "" Then
strWhere = "WHERE tblOpenJobs.[JobDate] > #" & FormatDateTime(Date, vbShortDate) & "#"
Else
strWhere = strWhere & " AND tblOpenJobs.[JobDate] > #" & FormatDateTime(Date, vbShortDate) & "#"
End If
End If
' Always include as part of the where clause, a section that
' will narrow the results based on who the user is
If strWhere = "" Then
strWhere = "WHERE tblOpenJobs.[OpenJobID] Not In " & _
"(SELECT tblSignUps.[OpenJobID] FROM tblSignUps WHERE tblSignUps.[EUID] = '" & strEUID & "');"
Else
strWhere = strWhere & " AND tblOpenJobs.[OpenJobID] Not In " & _
"(SELECT tblSignUps.[OpenJobID] FROM tblSignUps WHERE tblSignUps.[EUID] = '" & strEUID & "');"
End If
' Concatenate the Select and the Where clause together
strSql = strSql & " " & strWhere
' Set the recordsource of the subform to the SQL query generated
' and refresh the form.
Me.subQryOpenJobs.Form.RecordSource = strSql
' In addition, synchronize the JobID's in the Edit Job box to match those
' filtered by this Build Query.
Me.cboSelectJOBID.RowSource = "SELECT tblOpenJobs.[OpenJobID] FROM tblOpenJobs" & " " & strWhere
Me.Refresh
End Sub`
(2) Main Form. http://j.imagehost.org/view/0385/Form. and (3) the subform is populated as shown in the BuildQuery() sub to construct the query based on what the user selects from the drop down filters and the input boxes on the right of the form. The data in the table itself is inaccessible to the user, this is just for them to reference.