Access Query based on a form with multiple checkboxs - ms-access

I can't seem to find any answers here for my specific problem. Maybe it's because I don't know what I'm looking for...
Anyway, I have an Access form that has about 30 checkboxes for each live facility we have and I need to run a query (which works perfectly) based on what boxes are ticked and a begin and end date which are also on the form.
This is the SQL I have (generated by the Query Wizard) that shows every single facility for every single date.
TRANSFORM Count(tblFilesProcessed.[File Name]) AS [CountOfFile Name]
SELECT tblFilesProcessed.[Fac Alpha], tblFilesProcessed.[File Date], Count(tblFilesProcessed.[File Name]) AS [Total Of File Name]
FROM tblFilesProcessed
GROUP BY tblFilesProcessed.[Fac Alpha], tblFilesProcessed.[File Date]
PIVOT tblFilesProcessed.[File Type];
I need to be able to pick and choose what I want the report to show. Right now it shows Facility01 all the way through Facility30 for dates going back to March. I need to be able to tick a box for Facility04, Facility 15, and Facility 20 for the past week. Or Facility 03, 21, 22, 23, 24.

What you will need to do is to use VBA to look at the controls on the form, and build up a modified SQL statement which you will then set to be the query's .SQL. Something like this:
Private Sub cmdQuery_Click()
On Error GoTo E_Handle
Dim strWhere As String
Dim strSQL1 As String
Dim strSQL2 As String
strSQL1 = "TRANSFORM Count(F.[File Name]) AS [CountOfFile Name] " _
& " SELECT F.[Fac Alpha], F.[File Date], Count(F.[File Name]) AS [Total Of File Name] " _
& " FROM tblFilesProcessed AS F "
strSQL2 = " GROUP BY F.[Fac Alpha], F.[File Date] " _
& " PIVOT F.[File Type];"
If Me!chkFac1 = True Then strWhere = strWhere & "'Fac1',"
If Me!chkFac2 = True Then strWhere = strWhere & "'Fac2',"
If Len(strWhere) > 0 Then
strWhere = " AND F.[Fac Alpha] IN(" & Left(strWhere, Len(strWhere) - 1) & ") "
End If
If IsDate(Me!txtFrom) Then
strWhere = strWhere & " AND F.[File Date]>=" & Format(Me!txtFrom, "\#mm\/dd\/yyyy\#")
End If
If IsDate(Me!txtTo) Then
strWhere = strWhere & " AND F.[File Date]<=" & Format(Me!txtTo, "\#mm\/dd\/yyyy\#")
End If
If Left(strWhere, 4) = " AND" Then
strWhere = " WHERE " & Mid(strWhere, 5)
End If
CurrentDb.QueryDefs("qryFilesProcessed").SQL = strSQL1 & strWhere & strSQL2
sExit:
On Error Resume Next
Exit Sub
E_Handle:
MsgBox Err.Description & vbCrLf & vbCrLf & "frmFilesProcessed!cmdQuery_Click", vbOKOnly + vbCritical, "Error: " & Err.Number
Resume sExit
End Sub
I would suggest that rather than using 30 checkboxes, a multi-select list box would be better, as it allows for future proofing - indeed, you could set its .RowSource to be the list of unique Facility values from the table.

Related

MS Access Table filtered by checkboxes from a form, creating a new table

I want to create a new table "TblMany", filtering values from other data table "TblControl".
Filtering with multiple checkboxes of a Form "FrmMany".
Table with data "TblControl":
Form with checkboxes, representing all values available in "Box?" columns from data table:
After pressing the button, it should create a new table (or recreate one existing) that shows rows with numbers selected in the "FrmMany"
Multiple selection needed:
I have done some tests with "iif" or "where" but i think it's only possible via VBA.
Any ideas?
You are correct that you will need to use VBA to do this. Firstly, you will need to loop the checkboxes to see if they are to be used in the selection of data. Once this has been done, you need to build a SQL string that inserts the data into the existing table. Something like this seems to work:
Private Sub cmdProcess_Click()
On Error GoTo E_Handle
Dim intLoop1 As Integer
Dim strSQL As String
For intLoop1 = 1 To 8
If Me("chk" & intLoop1) = True Then strSQL = strSQL & intLoop1 & ","
Next intLoop1
If Len(strSQL) > 0 Then
If Right(strSQL, 1) = "," Then strSQL = Left(strSQL, Len(strSQL) - 1)
CurrentDb.Execute "DELETE * FROM tblMany;"
CurrentDb.Execute "INSERT INTO tblMany " _
& " SELECT * FROM tblControl " _
& " WHERE Box1 IN(" & strSQL & ") " _
& " OR Box2 IN(" & strSQL & ") " _
& " OR Box3 IN(" & strSQL & ");"
End If
sExit:
On Error Resume Next
Exit Sub
E_Handle:
MsgBox Err.Description & vbCrLf & vbCrLf & "cmdProcess_Click", vbOKOnly + vbCritical, "Error: " & Err.Number
Resume sExit
End Sub
I am assuming that tblMany is an exact copy of of tblControl apart from field ID being an Autonumber in tblControl and just numeric in tblMany.
Rather than repeatedly deleting and inserting data (which will lead to bloat), you may find it better to use a query and modify its SQL as needed:
CurrentDb.QueryDefs("qryMany").SQL="SELECT * FROM tblControl " _
& " WHERE Box1 IN(" & strSQL & ") " _
& " OR Box2 IN(" & strSQL & ") " _
& " OR Box3 IN(" & strSQL & ");"

Creating a form to search for records based on multiple criteria

I am trying to create a form that allows you to return results based on multiple criteria.
I have FirstName field, LastName field, and State Field.
I also have an text boxes named searchFirst, searchLast, searchState where users can input criteria.
The search button will execute the following code once clicked.
Private Sub mySearchQuery_Click()
Dim filter As String
Dim rtFirstName As String
Dim rtLastName As String
Dim rtState As String
rtFirstName = Me.searchFirst.Value
rtLastName = Me.searchLast.Value
rtState = Me.searchState.Value
If Not IsNull(rtFirstName) Then
If Not IsNull(filter) Then filter = filter & " AND "
filter = filter & "(FirstName like""*" & rtFirstName & "*"")"
End If
If Not IsNull(rtLastName) Then
If Not IsNull(filter) Then filter = filter & " AND "
filter = filter & "(LastName like""*" & rtLastName & "*"")"
End If
If Not IsNull(rtState) Then
If Not IsNull(filter) Then filter = filter & " AND "
filter = filter & "(State LIKE""*" & rtState & "*"")"
End If
' Now re-construct the SQL query '
Dim sql As String
sql = "SELECT * FROM MainData"
If Not IsNull(filter) Then
sql = sql & " WHERE " & filter
End If
Me.RecordSource = sql
'SubForm.Form.RecordSource = sql
End Sub
I am getting the following error below.
Run-time error '3075': Syntax error (missing operator) in query
expression 'AND (FirstName like"*tracy*") AND (lastName like"*Smith*")
AND (State LIKE"*ga*")'.
I am not sure why AND was included at the beginning of the search query?
I am not sure why AND was included at the beginning of the search
query?
Since you have Dim filter As String, filter can never contain Null. That means these If conditions ... If Not IsNull(filter) ... will always be True.
Similarly, Not IsNull(rtFirstName), Not IsNull(rtLastName), and Not IsNull(rtState) will always be True.
The net result is the code adds another condition piece to your filter string regardless of whether or not the corresponding search text box contains anything, and each of those pieces is prefixed with " AND ".
With those points in mind, you could refactor your code to add a filter segment only when you have something in the corresponding search text box and decide when to include " AND ". However I find it simpler to include " AND " for each of them and then strip away the very first " AND " from filter before adding it to the WHERE clause.
Private Sub mySearchQuery_Click()
Dim strSelect As String
Dim strWhere As String
If Len(Trim(Me!searchFirst.Value) & vbNullString) > 0 Then
strWhere = strWhere & " AND FirstName Like ""*" & Me!searchFirst.Value & "*"""
End If
If Len(Trim(Me!searchLast.Value) & vbNullString) > 0 Then
strWhere = strWhere & " AND LastName Like ""*" & Me!searchLast.Value & "*"""
End If
If Len(Trim(Me!searchState.Value) & vbNullString) > 0 Then
strWhere = strWhere & " AND State Like ""*" & Me!searchState.Value & "*"""
End If
' Now re-construct the SQL query
strSelect = "SELECT * FROM MainData"
' only add WHERE clause if we have something in strWhere
If Len(strWhere) > 0 Then
' use Mid() to ignore leading " AND "
strSelect = strSelect & " WHERE " & Mid(strWhere, 6)
End If
Debug.Print strSelect ' <- inspect this in Immediate window; Ctrl+g will take you there
' enable one of these RecordSource lines after confirming Debug.Print shows you what you need
'Me.RecordSource = sql
'SubForm.Form.RecordSource = sql
End Sub

Access VBA Coding & Form Linking

I have a form called "Search Issues' and a Subform within call "Browse All Issues". Browse All Issues Record source is a table that contains all the data called Issues. I'm trying to create search features within "Search Issues" where I can select multiple criteria from List box and when I click Search Browse all issues filter on the criteria I selected. I currently I the following code:
Private Sub Search_Click()
On erorr GoTo errr
Me.Search.Form.RecordSource = "SELECT * From Browse_All_IssuesSubform " & BuildFilter
Me.Search.Form.Requery
Exit Sub
errr:
MsgBox Err.Description
End Sub
Private Function BuildFilter() As Variant
Dim strWhere As String
strWhere = IIf(Len(Me.AssignedTo & "") <> 0, "([AssignedTo] Like ""*" & Me.AssignedTo & "*"") AND", "") & _
IIf(Len(Me.OpenedBy & "") <> 0, "([OpenedBy] Like ""*" & Me.OpenedBy & "*"") AND", "") & _
IIf(Len(Me.Status & "") <> 0, "([Status] Like ""*" & Me.Status & "*"") AND", "") & _
IIf(Len(Me.Category & "") <> 0, "([Category] Like ""*" & Me.Category & "*"") AND", "") & _
IIf(Len(Me.Priority & "") <> 0, "([Priority] Like ""*" & Me.Priority & "*"") AND", "") & _
IIf(Len(Me.OpenedDateFrom & "") <> 0, "([EnteredOn] >= #" & Format(Me.OpenedDateFrom, "mm/dd/yyyy") & "#) AND", "") & _
IIf(Len(Me.DueDateFrom & "") <> 0, "([EnteredOn] <= #" & Format(Me.DueDateFrom, "mm/dd/yyyy") & "#) AND", "")
If Len(strWhere & "") = 0
Then
MsgBox "No criteria", vbInformation, "Nothing to do."
Else
Me.Filter = Left(strWhere, Len(strWhere & "") - 4)
Me.FilterOn = True
Me.Requery
End If
BuildFilter = strWhere
End Function
How can I get his to work? When I run the event I get the message "Compile Error" : Method or data member not found.
Please help
If it runs without errors but doesn't filter correctly, you probably got the WHERE clause wrong.
First of all, the word WHERE is completely missing in the SQL string that you're building!
But I don't know if that's all.
Without knowing your database tables (definition and the data inside!), it's very hard for us to find any mistakes in your query.
So you should try to find out by yourself, step by step:
In the Search_Click() sub, output the final SQL string to the Immediate Window:
Debug.Print "SELECT * From Browse_All_IssuesSubform " & BuildFilter
Create a new Access query, switch to SQL view, copy & paste the SQL string from the Immediate Window. Try to run the query.
Does it return more rows than you expected?
Then there's something missing in the WHERE clause. Look at the rows which you didn't expect to be returned, and think about what needs to be added to the WHERE clause to make them disappear from your result set.
Does it return less rows than you expected (or none at all)?
Then you are filtering too much. Try to delete parts of your WHERE clause, step by step, and each time run the query again until you get all the rows that you want.
This should be enough to point you into the right direction.
If you still aren't able to find the mistake, we need much more information.

Export data from continuous form to Excel w/o header fields

I have a continuous form, where the form header contains filter options, and the details section contains the data.
I want to be able to export this to excel. the basic VBA code works
DoCmd.OutputTo
but when I export to Excel, it also includes the form header controls for each row.
Is there any way to set a property that will exclude the form header from being included in the export? Basically, only export the form details section?
I prefer not to use a query
I have 6 unbound txt boxes in the header:
- artnr
- Artnr supplier
- description
- article status
- supplier name
- supplier number
and i have a search button, wich holds this code:
Private Sub cmdSearch_Click()
Dim strWhere As String
Dim lngLen As Long
'artikel zoeken
If Not IsNull(Me.txtSearchArtnr) Then
strWhere = strWhere & "([Material] Like ""*" & Me.txtSearchArtnr & "*"") AND "
End If
'artnr leverancier zoeken
If Not IsNull(Me.txtSearchSupplArt) Then
strWhere = strWhere & "([LiefMat] Like ""*" & Me.txtSearchSupplArt & "*"") AND "
End If
'trefwoord zoeken
If Not IsNull(Me.txtSearchKeyword) Then
strWhere = strWhere & "([Materialkurztext] Like ""*" & Me.txtSearchKeyword & "*"") AND "
End If
'artikelstatus zoeken
If Not IsNull(Me.txtSearchStatus) Then
strWhere = strWhere & "([Status] Like ""*" & Me.txtSearchStatus & "*"") AND "
End If
'leverancier naam zoeken
If Not IsNull(Me.txtSearchSupplName) Then
strWhere = strWhere & "([Name 1] Like ""*" & Me.txtSearchSupplName & "*"") AND "
End If
'leverancier nummer zoeken
If Not IsNull(Me.txtSearchSupplNumber) Then
strWhere = strWhere & "([Lieferant] Like ""*" & Me.txtSearchSupplNumber & "*"") AND "
End If
'***********************************************************************
'Chop off the trailing " AND ", and use the string as the form's Filter.
'***********************************************************************
'See if the string has more than 5 characters (a trailng " AND ") to remove.
lngLen = Len(strWhere) - 5
If lngLen <= 0 Then 'Nah: there was nothing in the string.
MsgBox "Geen criteria gevonden", vbInformation, "Geen resultaten."
Else 'Yep: there is something there, so remove the " AND " at the end.
strWhere = Left$(strWhere, lngLen)
'Apply the string as the form's Filter.
Me.Filter = strWhere
Me.FilterOn = True
End If
End Sub
I found the sollution here:
Exporting selected records to excel - hiding certain columns
DoCmd.Echo False
Me.Field1.Visible = False
Me.Field2.Visible = False
Me.Field3.Visible = False
DoCmd.RunCommand acCmdOutputToExcel
Me.Field1.Visible = True
Me.Field2.Visible = True
Me.Field3.Visible = True
DoCmd.Echo True
End Sub
it's simple and it works for me
you write, that users can set filters, so you must have programmed something like
Me.RecordSource = "SELECT ... FROM table WHERE --here the criterias--"
Me.Requery
so you could take the SQL-Statement and use it for export, you first have to create a query
Dim sSQL As String
Dim qd As QueryDef
Set qd = CurrentDb.CreateQueryDef("tmp_Query")
qd.SQL = "Select * from T_Personal"
DoCmd.TransferSpreadsheet acExport, acSpreadsheetTypeExcel12, "tmp_Query", "yourfile", True
CurrentDb.QueryDefs.Delete qd.Name
wrap it into a function, so you can fire it anywhere and pass the sql and filename ...
HTH

What does "Too few parameters. Expected 1." on MS Access mean?

I'm trying to update records in my form. It's a restaurant reservation system. Given the Table #, the form can let the user input the Customer ID of the person reserving, the reservation time and date. But when I click on the "update" button in my form, a text box will pop up with this:
And whatever I put in it, the runtime error "too few parameters. expected 1." pops up. Sometimes a "Reserved Error" will pop up. Could someone help me? It's the last step before I could finally finish this project.
This is my code for updating the record:
Private Sub Command8_Click()
On Error GoTo errHandling
Dim strSQL As String
strSQL = "UPDATE tblReserve SET CustomerID = " & """" & Me.txtCustID & """" & _
", ResDate = " & """" & Me.txtResDate & """" & ", ResTime = " & """" & Me.txtTime & """" & " WHERE TableNum =" & Me.TableNum
DoCmd.SetWarnings False
DoCmd.RunSQL strSQL
DoCmd.SetWarnings True
CurrentDb.Execute strSQL, dbFailOnError
DoCmd.Close
Exit Sub
errHandling:
MsgBox Err.Description
End Sub
Screenshot of VBA editor with Debug.Print strSQL
As revealed in our [chat][1], the essence of the problem was that [TableNum] is a text field and therefore its value had to be enclosed in quotes:
"... WHERE TableNum = '" & Me.TableNum & "'"
[1]: https://chat.stackoverflow.com/rooms/42746/discussion-between-nutellafella-and-gord-thompson)
Try something like this
strSQL = "UPDATE tblReserve SET CustomerID = " & Me.txtCustID & _
", ResDate = " & "'" & Me.txtResDate & "'" & ", ResTime = " & "'" & Me.txtTime & "'" & " WHERE TableNum =" & Me.TableNum
I am not sure why you have 2 sets of double quotes inside double quotes, I think what you were looking for is single quotes :)
However, there are much better ways to format sql than this. Also this seems like homework, so study up!