--
I badly need your help guys. I'm stuck with these problems for a almost a month . I need to get the time and date if the user tap on the scanner.
Private Sub Command1_Click()
Adodc1.RecordSource = "select * from tbl_login where user = '" + Text1.text + "'"
Adodc1.Refresh
If Adodc1.Recordset.EOF Then
MsgBox "Login Failed", vbCritical + vbOKOnly, "Error"
Else
Adodc1.RecordSource = "update tbl_login set dte = '" & Label1.Caption & "' set tme '" & Label2.Caption & "' where user = '" + Text1.text + "'"
MsgBox "Login Successful!", vbExclamation + vbOKOnly, "Welcome"
Text1.text = ""
Text2.text = ""
End If
End Sub
Private Sub Timer1_Timer()
Label1.Caption = Format(Now, "dddd mmmm dd, yyyy")
Label2.Caption = Format(Now, "hh: mm: ss ampm")
End Sub
It shows the Login Successful, but it doesn't record the time and date of the user.
Help please, help me fix this.
Simply insert date and time:
Adodc1.RecordSource = "update tbl_login set dte = Date(), tme = Time() where user = '" & Text1.text & "'"
Firstly, I would suggest always using the ampersand operator (&) for string concatenation, not the addition operator (+).
Assuming that your fields dte and tme are datetime fields, then the reason that your UPDATE query fails is because you are not providing the date & time data in an appropriate format required for SQL.
However, rather than using concatenation to insert the data into your UPDATE query, I would instead suggest parameterising the query and passing the date, time, and username to the parameters, for example:
With CurrentDb.CreateQueryDef("", "update tbl_login set tbl_login.dte = #dte, tbl_login.tme = #tme where tbl_login.user = #usr")
.Parameters(0) = Date
.Parameters(1) = Now
.Parameters(2) = Text1.Text
.Execute
End With
You can find out more about parameterised queries from this excellent answer.
Related
I have a form contains of 3 listboxes that will filter my report based on the selected items
in my query I used the below criteria for the combobox and I tried it on the listbox but it does not work!
Like [Forms]![Statusfrm]![FieldCombo] & "*"
any advise please?
I also tried this but when I select one selection it is not showing records for the same selection!
Private Sub Command26_Click()
On Error GoTo ControlError
Set ctl = Me.Combo22 'frm!Combo22
Set ctl2 = Me.Combo24
'Set rpt = Foms!rpt
If Me.Combo22.ListIndex <> -1 Then 'And Me.Combo24.ListIndex <> -1
miFiltro = "id in("
For Each varItm In ctl.ItemsSelected
'miFiltro = miFiltro & "'" & varItm & "',"
miFiltro = miFiltro & varItm & ","
'Lista27.AddItem varItm
'ctl.ItemData (varItm)
Next varItm
miFiltro = Mid(miFiltro, 1, Len(miFiltro) - 1)
miFiltro = miFiltro & ")"
'MsgBox (miFiltro)
If miFiltro <> "" Then
DoCmd.OpenReport "Rpt", acViewPreview, , miFiltro
miFiltro = ""
End If
'Aplicamos el filtro al formulario
'Me.Filter = miFiltro
'Me.FilterOn = True
Else
MsgBox ("Please select data")
Me.Combo22.SetFocus
End If
'DoCmd.OpenReport "Rpt", acPreview, , Me.Filter
ControlError:
MsgBox "Encontré el error" & Err.number & " " & Err.Description
End Sub
You can change your Report to be based on a fixed DB query. When the user clicks the "View Report" button, add the code:
Dim strSQL As String
strSQL = "SELECT * FROM YourTable WHERE [Place] = '" + Me!Statusfrm + "'"
CurrentDB.QueryDefs("TheAccessQueryObjectTheReportIsBasedOn").SQL = strSQL
DoCmd.OpenReport "YourReport"
In this model, you are setting the SQL of the Query object at the Access DB container level, then opening the report. You can debug your VBA code more easily this way, instead of relying on a RecordSource query with a runtime parameter referencing the form. You can also close the form if you want to before opening the report.
The WHERE condition for your strSQL variable can be built up based on input (or lack thereof) from the user. For example:
If Nz(First(Me!categoryListBox.SelectedItems).Value,"") <> "" Then
strSQL = strSQL + " AND [Category] = '" Me!categoryListBox.SelectedItems).Value + "'"
End
If Nz(First(Me!placeListBox.SelectedItems).Value,"") <> "" Then
strSQL = strSQL + " AND [Place] = '" Me!placeListBox.SelectedItems).Value + "'"
End
Also, is your list box bound to an ID or the text of the item selected? You may be getting an ID vs the text you are trying to use with the asterisk wildcard. A list box can have multiple selections, so you need to disable it, or do something like :
strSQL = "SELECT * FROM YourTable WHERE [Place] = '" + First(Me!statusfrm.SelectedItems).Value + "'"
If the user can only select one value, a combobox it the better choice. Either way, by building up an SQL statement in VBA that uses the forms value, you can debug the syntax of the SQL more easily.
I Have this code, and I can't figure out what is wrong with it. It does not return any error but field Date_Returned is not getting updated. Please help.
Private Sub txtbxret_Click()
Dim query As String
query = "UPDATE Rent SET Date_Returned = '" & Date & "' WHERE Date_Rent = " & txtrented.Value & " AND Customer_ID = " & txtbxcustID.Value & " AND Movie_ID = " & txtbxmovID.Value
DoCmd.RunSQL (query)
End Sub
I've double and triple checked all the field names and thay are ok by the way...
You must use proper formatting of string expressions of date values in SQL:
query = "UPDATE Rent SET Date_Returned = Date() WHERE Date_Rent = #" & Format(txtrented.Value, "yyyy\/mm\/dd") & "# AND Customer_ID = " & txtbxcustID.Value & " AND Movie_ID = " & txtbxmovID.Value
I have some VBA code that will update a table based on a form. It works great, except that I want the table to only update wherever the user fill in info. If that textbox is instead blank, do no update that field in the table. Below is the working update code. The line that starts with If query.Parameters("P1")... is my attempt at trying to make an If statement that will find which textbox values are Null and then ignore those, but I don't know if that's even going in the right direction.
Private Sub Command133_Click()
'Update row for downtime
Dim dbsCurrent As Database
Set dbsCurrent = CurrentDb
', suffix, production_date, reason, downtime_minutes, comment ,'" & CInt(Me.Text118) & "','" & CDate(Me.Text126) & "','" & Me.Text121 & "','" & CDbl(Me.Text123) & "','" & Me.Text128 & "'
'dbsCurrent.Execute " INSERT INTO tbl_Downtime (production_date) SELECT #" & Me.Text126 & "# FROM tbl_Downtime As t WHERE t.ID = " & Me.Text135 & ";"
'dbsCurrent.Execute "UPDATE tbl_Downtime SET job = '" & Me.Text116 & "', suffix = '" & Me.Text118 & "', production_date = #" & Me.Text126 & "#, reason = '" & Me.Text121 & "', downtime_minutes = " & Me.Text123 & ", comment = '" & Me.Text128 & "', shift = '" & Me.Text144 & "' WHERE t.ID = " & Me.Text135 & ";"
Dim query As QueryDef
Dim sql As String
For Each query In CurrentDb.QueryDefs
If query.Name = "UpdateDowntime" Then
Exit For
End If
Next query
If query Is Nothing Then
sql = "parameters " & _
"P1 text, P2 text, P3 Date, P4 Text, P5 Number, P6 Text, P7 Text, P8 Number;" & _
"UPDATE [tbl_Downtime] " & _
"SET job = [P1], suffix = [P2], production_date = [P3], reason = [P4], downtime_minutes = [P5], comment = [P6], shift = [P7] " & _
"WHERE[tbl_Downtime].id = [P8]"
'"(job, suffix, production_date, reason, downtime_minutes, comment, shift) " & _
'" VALUES ([P1], [P2], [P3], [P4], [P5], [P6], [P7]) WHERE[tbl_Downtime].id = [P8]"
Set query = CurrentDb.CreateQueryDef("UpdateDowntime", sql)
End If
query.Parameters("P1").Value = Me.Text116
query.Parameters("P2").Value = Me.Text118
query.Parameters("P3").Value = Me.Text126
query.Parameters("P4").Value = Me.Text121
query.Parameters("P5").Value = Me.Text123
query.Parameters("P6").Value = Me.Text128
query.Parameters("P7").Value = Me.Text144
query.Parameters("P8").Value = Me.Text135
If query.Parameters("P1").Value = "" Then Set query.Parameters("P1").Value = job End If ' WHERE [tbl_Downtime].id = [P8] END
query.Execute
An empty string is not the same as a null value in a database, so you need to change the parameter value to nothing if you want it to equate to null (or default value if one exists).
You could either conditionally set the parameter value like this:
If textbox1.text <> "" then
query.Parameters("P1").Value = textbox1.text
End if
or you could write a function to set the parameter to nothing if the textbox is empty:
Function NothingIfEmpty(value As String)
If value = "" Then
NothingIfEmpty = Nothing
Else
NothingIfEmpty = value
End If
End Function
and use it like this:
query.Parameters("P1").Value = NothingIfEmpty(textbox1.text)
query.Parameters("P2").Value = NothingIfEmpty(textbox2.text)
You can do it this way:
"SET job = Nz([P1], job), suffix = Nz([P2], suffix), production_date = Nz([P3], production_date), reason = Nz([P4], reason), downtime_minutes = Nz([P5], downtime_minutes), comment = Nz([P6], comment), shift = Nz([P7], shift) " & _
"WHERE [tbl_Downtime].id = Nz([P8], -[id])"
I have an expenditures subform in Access 2010 that lists the predicted costs associated with the project for each year. Most projects only have one year, but some have more than one. Each cost has a Final checkbox next to it that should be checked when the amount is confirmed, ie. at the end of each year.
It basically looks something like this:
Year | Cost | Final
--------+-----------+--------------------
2017 | $100 | [checked box]
2018 | $200 | [unchecked box]
| | [unchecked box]
I have another field outside the table, FinalCost, that adds up everything in the Cost field. Right now, it fills in the amount from any year which has a checked Final box. That should only be filled when all the Final boxes are checked.
Ex. Right now, it should show nothing even though Final for 2017 is checked. When 2018 is checked, it should show $300. Instead, it shows $100 even though there's still an empty checkbox.
This is the code for this form.
Private Sub Form_AfterUpdate()
Dim rs1, rs2 As Recordset
Dim sql, sql2 As String
sql = "SELECT Sum(Amount) as Final From Expenditures " & _
"Where ProjNo = '" + Me.ProjNo + "' And Final = True Group by ProjNo"
sql2 = "SELECT FinalExpenditure From ActivityCash " & _
"Where ProjNo = '" + Me.ProjNo + "'"
Set rs1 = CurrentDb.OpenRecordset(sql, dbOpenDynaset, dpinconsistent)
Set rs2 = CurrentDb.OpenRecordset(sql2, dbOpenDynaset, dpinconsistent)
If rs1.RecordCount > 0 Then
If rs2.RecordCount > 0 Then
Do While Not rs2.EOF
rs2.Edit
rs2!FinalExpenditure = rs1!Final
rs2.Update
rs2.MoveNext
Loop
End If
End If
rs2.Close
rs1.Close
Set rs1 = Nothing
Set rs2 = Nothing
End Sub
What would be the best way to go about doing this?
EDIT: When the last box is checked, a new row is automatically added with an untoggled checkbox but no information.
Replace the statement beginning with sql = ... with this:
sql = "SELECT SUM(e1.Amount) AS Final " & _
" FROM Expenditures AS e1 " & _
" WHERE NOT EXISTS (SELECT 'x' FROM Expenditures e2 WHERE e2.Final=0 AND e1.ProjNo = e2.ProjNo) " & _
" AND e1.ProjNo = '" & Me.ProjNo & "'"
This query will return data only if there are all expeditures for the project marked as final. As you check for rs1.RecordCount > 0 there will be no update if this query returns no records.
So, before sql, I would verify that all records have True in your Final field.
To do that, let's just return a COUNT() of (any) records that have Final = False, and we can then decide to do what we want.
So, something like,
Dim Test as Integer
test = DCount("*", "YourTableName", "Final = False AND ProjNo = " & Me.ProjNo &"")
If test > 0 Then
'Don't fill the box
Else
'Fill the box, everything is True
'Read through your recordsets or whatever else you need to do
End If
To use a query, we essentially need to replicate the Dcount() functionality.
To do this, we need another Recordset variable, and we need to check the value of the Count() field from our query.
Create a query that mimicks this:
SELECT COUNT(*) As CountTest
FROM YourTable
HAVING Final = False
AND ProjNo = whateverprojectnumberyou'reusing
Save it, and remember that query's name.
Much like the DCount(), we need to make this "check" determine the route of your code.
Dim rst As DAO.Recordset
Set rst = CurrentDb.OpenRecordset("YourQuery'sNameHere")
If rst!CountTest > 0 Then
'They are not all Checked (aka True)
Else
'Supply the value to the FinalCost
End If
Set rst = Nothing
Change this:
sql = "SELECT Sum(Amount) as Final From Expenditures " & _
"Where ProjNo = '" + Me.ProjNo + "' And Final = True Group by ProjNo"
For this:
"SELECT SUM(Amount) - SUM(IIF(Final,1,0)*Amount) as YetToConfirm, SUM(Amount) as Confirmed From Expenditures " & _
"Where ProjNo = '" + Me.ProjNo + "' Group by ProjNo"
rs1 will return two values, the total value if all costs were confirmed in the rs1!Confirmed, and the value yet to confirm in rs1!YetToConfirm
Then here:
Do While Not rs2.EOF
rs2.Edit
rs2!FinalExpenditure = rs1!Final
rs2.Update
rs2.MoveNext
Loop
change it to:
Do While Not rs2.EOF
rs2.Edit
rs2!FinalExpenditure = Iif(rs1!YetToConfirm = 0, rs1!Confirmed, 0)
rs2.Update
rs2.MoveNext
Loop
One way to process this would be check using a subquery whether last year(verified using a dmax function) in each project has been checked in the final column, if this is true, get your sum of checked amounts, else dont calculate the sum.
I have modified your sql string to include this and I tested it against your given example to confirm its showing a sum of $300 or nothing.
SQL = ""
SQL = SQL & " SELECT Sum(Amount) as Final From Expenditures "
SQL = SQL & " Where ProjNo = '" & Me.ProjNo & "' And Final = True "
SQL = SQL & " And (SELECT Expenditures.Final FROM Expenditures where year = ( "
SQL = SQL & " DMax('Year','Expenditures','ProjNo= " & Chr(34) & Me.ProjNo & Chr(34) & "'))) = true "
SQL = SQL & " Group by ProjNo "
I am trying to access certain lines from my SQL database from MSAccess and I keep getting an Invalid Argument Error on this line:
Set rs = CurrentDb.OpenRecordset("SELECT TimeID " & _
"FROM tblLunchTime " & _
"WHERE ProductionID = prodSelect AND EndTime is NULL AND StartTime < dateAdd('h', 3, NOW())", [dbSeeChanges])
Is something not right in this?
Private Sub cmdClockEnd_Click()
'Check if a group has been selected.
If frmChoice.value = 0 Then
MsgBox "Please select a production line."
End
End If
'Setup form for user input.
lblEnd.Visible = True
'Save end of lunch value.
lblEnd.Caption = Format(Now, "MMM/DD/YY hh:mm:ss AMPM")
'Declare database variables.
Dim dbName As DAO.Database
Dim strValuesQuery As String
Dim rs As DAO.Recordset
Dim prodSelect As String
Dim sSQL As String
Dim timeValue As String
Set dbName = CurrentDb
'Get values of Production Line.
If frmChoice.value = 1 Then
prodSelect = "L2"
ElseIf frmChoice.value = 2 Then
prodSelect = "L3"
End If
'Get the last TimeID with the following parameters.
sSQL = "SELECT TimeID " & _
"FROM tblLunchTime " & _
"WHERE ProductionID = prodSelect AND EndTime is NULL AND StartTime < #" & DateAdd("h", 3, Now()) & "#"
Set rs = dbName.OpenRecordset(sSQL, dbSeeChanges)
strValuesQuery = _
"UPDATE tblLunchTime " & _
"SET EndTime = '" & Now & "'" & _
"WHERE TimeID = " & rs![TimeID] & " "
'Turn warning messages off.
DoCmd.SetWarnings False
'Execute Query.
DoCmd.RunSQL strValuesQuery
'Turn warning messages back on.
DoCmd.SetWarnings True
End Sub
You need to put prodSelect outside the quotes:
"WHERE ProductionID = " & prodSelect & " AND ...
It is nearly always best to say:
sSQL="SELECT TimeID " & _
"FROM tblLunchTime " & _
"WHERE ProductionID = " & prodSelect & _
" AND EndTime is NULL AND StartTime < dateAdd('h', 3, NOW())"
''Debug.print sSQL
Set rs = CurrentDb.OpenRecordset(sSQL)
You can see the advantage in the use of Debug.Print.
AHA prodSelect is text! You need quotes!
sSQL="SELECT TimeID " & _
"FROM tblLunchTime " & _
"WHERE ProductionID = '" & prodSelect & _
"' AND EndTime is NULL AND StartTime < dateAdd('h', 3, NOW())"
There appears to be confusion about tblLunchTime ... whether it is a native Jet/ACE table or a link to a table in another database. Please show us the output from this command:
Debug.Print CurrentDb.TableDefs("tblLunchTime").Connect
You can paste that line into the Immediate Window and press the enter key to display the response. (You can open the Immediate Window with CTRL+g keystroke combination.)
Just in case the response starts with "ODBC", suggest you try this line in your code:
Set rs = CurrentDb.OpenRecordset(sSQL, dbOpenDynaset, dbSeeChanges)
Update: Now that you're past that hurdle, suggest you change your approach with the UPDATE statement. Don't turn off warnings; try something like this instead:
'Execute Query. '
CurrentDb.Execute strValuesQuery, dbFailOnError
And add an error handler to deal with any errors captured by dbFailOnError.
I think I would do the date criterion concatenation client-side, too, since it's one more thing that could go wrong:
"...StartTime < #" & DateAdd("h", 3, Now()) & "#"
I don't know that SQL Server doesn't have DateAdd() and Now() function nor that they don't behave exactly the same as in Access, but I wouldn't take the chance -- I'd do this calculation on the client instead of handing it off to the server.