I have a combo box on a form that I use to search for record based on [WorkDate] and it works fine. the problem i have is that the combo box has 3 columns but it only does the lookup based on the first column. The columns in the combobox dropdown are WorkDate | WorkType | Comment
here is the code i have:
`Private Sub ctlSearch_AfterUpdate()
On Error GoTo myError
Dim rst As DAO.Recordset
Set rst = Me.RecordsetClone
rst.FindFirst "[WorkDate] = " & "#" & Format(Me.ctlSearch.Column(0), "yyyy/mm/dd") & "#" And "[WorkType] = '" & Me.ctlSearch.Column(1) & "'"
Me.Bookmark = rst.Bookmark
leave:
Me!ctlSearch = Null
If Not rst Is Nothing Then Set rst = Nothing
Exit Sub
myError:
MsgBox "Record Not Found"
Resume leave
End Sub`
I have narrowed down the issue to this line in the code:
rst.FindFirst "[WorkDate] = " & "#" & Format(Me.ctlSearch.Column(0), "yyyy/mm/dd") & "#" And "[WorkType] = '" & Me.ctlSearch.Column(1) & "'"
Also whenever I replace the above line of code with
rst.FindFirst "[WorkDate] = " & "#" & Format(Me.ctlSearch.Column(0), "yyyy/mm/dd") & "#"
or
rst.FindFirst "[WorkType] = '" & Me.ctlSearch.Column(1) & "'"
it works perfectly but for the life of me I cant get the lookup to work together. I have spent days trying to get this to work. Any help will be much appreciate.
You have a typo in your line. When you tried to combine the statements it looks like you added some extra quotes around the AND part.
rst.FindFirst "[WorkDate] = " & "#" & Format(Me.ctlSearch.Column(0), "yyyy/mm/dd") & "#" And "[WorkType] = '" & Me.ctlSearch.Column(1) & "'"
rst.FindFirst "[WorkDate] = #" & Format(Me.ctlSearch.Column(0), "yyyy/mm/dd") & "# And [WorkType] = '" & Me.ctlSearch.Column(1) & "'"
When writing a query statement in VBA the needs to be a string contained in quotes like so.
rst.FindFirst "Field1 = #01/02/2014#"
If you want to change the date to be a variable of some sort you need to append it to the string like you did above.
rst.FindFirst "Field1 = #" & dateField & "#"
The difference between what I wrote and what you had is that you don't need to divide the string up and put quotes around every part. Quotes only need to surround the parts that aren't variables.
Related
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 & ");"
I'm trying to delete one value in a found recordset, not the whole record.
In this instance I want to delete:
[" & TempVars("Software") & "]='" & TempVars("Version").Value & "'"
It finds the record without error. It just deletes the whole record which is not what I want. I just need the software version deleted.
This is my code:
Dim rst0 As Recordset
Set rst0 = CurrentDb.OpenRecordset("SoftwareLicenses", dbOpenDynaset)
rst0.FindFirst "[SWID] = " & TempVars("SWID").Value & " AND [EmpID] = " & TempVars("EMPID").Value & " AND [SWVersion]= '" & TempVars("Version").Value & "'"
rst0.Delete
rst0.Close
Set rst0 = Nothing
Dim rst2 As Recordset
Set rst2 = CurrentDb.OpenRecordset("EmpSWDetails", dbOpenDynaset)
rst2.FindFirst "[EmpID] = " & TempVars("EMPID").Value & " AND [" & TempVars("Software") & "]='" & TempVars("Version").Value & "'"
rst2.Delete
rst2.Close
Set rst2 = Nothing
Your help is really appreciated.
Instead of deleting the field value I edited it, declaring the variable in the recordset the correct way.
rst2.Edit
rst2.Fields(Software) = ""
I have this code for a filter option in my form. I want to built on the code to include multiple fields but I'm not sure if that is possible or how I could do that.
Here is what I have so far:
If Not IsNull(Me.searchlat) Then
strWhere = strWhere & "([Status] = """ & Me.searchlat & """) AND "
End If
Me.Filter = strWhere
Me.FilterOn = True
This is how I attempted to add additional fields and failed:
strWhere = strWhere & "([Status] = """ & Me.searchlat & """) OR [workername] = """ & Me.searchlat & """) AND "
The number of brackets in your statement does not add up and the AND at the end is incorrect, because there is no further criteria linked by it.
Additionally I would recommend using single quotation marks inside the sql string. That makes clearer, which quotation mark has which purpose.
strWhere = strWhere & " [Status] = '" & Me.searchlat & "' OR [workername] = '" & Me.searchlat & "'"
The brackets had no effect in your excerpt at all therefore I removed them. But depending on the original where-condition in strWhere and the intention of your filter you might need to add some again.
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!
I've created a search tool that has a few issues I can't seem to iron-out. On the main form is a selection of text boxes for the user to enter search filters against and then a command button for them to execute the search and another command button for them to empty/reset the search text boxes.
Below the text boxes is a subform (set to continuous form), which displays the search results.
On the main form is this public function which builds up the WHERE clause for an SQL statement that will be used to update the subform's RecordSource (i.e. pass what was entered in the text boxes on the main form to the WHERE clause for the subform's search results.:
Public Function BuildFilter() As Variant
Dim varWhere As Variant
Dim tmp As String
tmp = """"
varWhere = Null
If Me.txtProspCode > "" Then
varWhere = varWhere & "[ProspectusCode] like " & tmp & "*" & Me.txtProspCode & "*" & tmp & " And "
End If
If Me.cboDeliveryOrg > "" Then
varWhere = varWhere & "[DeliveryOrganisation] like " & tmp & "*" & Me.cboDeliveryOrg & "*" & tmp & " And "
End If
If Me.cboLCdept > "" Then
varWhere = varWhere & "[LcDepartment] like " & tmp & "*" & Me.cboLCdept & "*" & tmp & " And "
End If
If Me.txtCollTitle > "" Then
varWhere = varWhere & "[ColloquialCourseTitle] like " & tmp & "*" & Me.txtCollTitle & "*" & tmp & " And "
End If
If Me.txtAimTitle > "" Then
varWhere = varWhere & "[LarsAimTitle] like " & tmp & "*" & Me.txtAimTitle & "*" & tmp & " And "
End If
If Me.txtAimRef > "" Then
varWhere = varWhere & "[LarsAimRef] like " & tmp & "*" & Me.txtAimRef & "*" & tmp & " And "
End If
If Me.cboCourseLevel > "" Then
varWhere = varWhere & "[CourseLevel] like " & tmp & "*" & Me.cboCourseLevel & "*" & tmp & " And "
End If
If Me.cboCourseType > "" Then
varWhere = varWhere & "[CourseType] like " & tmp & "*" & Me.cboCourseType & "*" & tmp & " And "
End If
If Me.cboAcYear > "" Then
varWhere = varWhere & "[Academic Year] like " & tmp & "*" & Me.cboAcYear & "*" & tmp & " And "
End If
If IsNull(varWhere) Then
varWhere = ""
Else
varWhere = "WHERE " & varWhere
If Right(varWhere, 5) = " And " Then
varWhere = Left(varWhere, Len(varWhere) - 5)
End If
End If
BuildFilter = varWhere
End Function
Also on the main form is the following code for when the user clicks the "search" button. It simply takes what was built for the WHERE clause in the above function and adds it to the appropriate place on the subform's RecordSource SQL statement:
Private Sub cmdSearch_Click()
Me.SearchSubForm.Form.RecordSource = "SELECT * FROM tblProspectus " & BuildFilter
Me.SearchSubForm.Requery
End Sub
And finally, also on the main form is the following code for when the user clicks the "clear search filters" button. It simply sets all search text boxes to 0-length strings and then sets the subform's record source to an empty row of results:
Private Sub cmdClear_Click()
Dim NoRecords As String
NoRecords = "SELECT " _
& "'' As ProspectusCode, " _
& "'' As DeliveryOrganisation, " _
& "'' As LcDepartment, " _
& "'' As LarsAimRef, " _
& "'' As LarsAimTitle, " _
& "'' As ColloquialCourseTitle, " _
& "'' As CourseLevel, " _
& "'' As CourseType, " _
& "'' As [Academic Year]"
Me.SearchSubForm.Form.RecordSource = NoRecords
Me.SearchSubForm.Requery
End Sub
Problems I'm having:
The "search" command is not returning any records when I try a search I know should return results in the subform. I've used Debug.Print Me.SearchSubForm.Form.RecordSource to see what was getting passed to the RecordSource and the SQL seemed fine to me... I even copy-pasted it in to the subform's Record Source manually in Design View and the form opened with the search results I was expecting... weird.
The "clear search filters" command works as long as I don't click the "search" command beforehand, otherwise it errors stating that the record source doesn't exist, quoting the SQL I passed in to the RecordSource for the "clear search filters" OnClick vba... again, weird. Almost as if the "Search" command's failure to produce records is causing an issue with any other attempt to change the subform's Record Source.
This subform, related command buttons and vba is working fine on a different main form! I'm pretty sure I've changed all references to this other main form I'm using...
Update:
I've found a workaround... I changed the table used in the SQL from a Table to a Query and now it seems to work fine... Don't know why though so would still appreciate any explanation.