Access VBA getting DateDiff results to work with Update SQL statement - ms-access

I'm using Access 2007 by itself with no connections to SQLserver or anything for this process.
I want to take the result of a few DateDiff functions and use an Update SQL statement to put them into fields on a table. My table's fields are number fields, and I am under the impression that DateDiff returns a number.
I try this, but I get a data type mismatch error on the first DateDiff (Pause1). I tried taking the quotes off of the fields but then I get a different error (can't find the field '|' referred to in your expression).
Here is my code. It really starts at the comment TIME REPORTING CODE HERE:
Private Sub StopNextButton_Click()
'
GetID = Forms!frm_MainMenu!AssocIDBox
CurRecord = Forms!frm_EC_L1_L2![L#].Value
'
DoCmd.RunSQL "UPDATE tbl_Data SET tbl_Data.[tsEndAll] = Now WHERE tbl_Data.[L#] = " & CurRecord & " AND (tbl_Data.[ECName] Like 'L1*' OR tbl_Data.[ECName] Like 'L2*') "
'
'TIME REPORTING CODE HERE'
'
Pause1 = DateDiff("s", "[tsPause1]", "[tsResume1]")
Pause2 = DateDiff("s", "[tsPause2]", "[tsResume2]")
ECTime = (DateDiff("s", "[tsECStart]", "[tsUpdated]") - (Pause1 + Pause2))
LTime = DateDiff("s", "[tsStartAll]", "[tsEndAll]")
'
DoCmd.RunSQL "UPDATE tbl_Data SET [ECTime] = " & ECTime & ", [LoanTime] = " & LTime & " WHERE tbl_Data.[L#] = " & CurRecord & " AND (tbl_Data.[ECName] Like 'L1*' OR tbl_Data.[ECName] Like 'L2*') "
'
'END OF TIME REPORTING CODE'
'
DoCmd.GoToRecord , , acNext
'
ETC.

Based off of your comment I assume that those fields are on the record your form is currently 'viewing'. If so you can just refer to them as Me.tsPause1 without [] or quotes. Pretty sure you can also do just tsPause1 but I find Me.tsPause1 makes it more obvious what you are doing.
However I think you are updating the field you are currently viewing and then immediately trying to access those updated fields. I am fairly certain you will need to a Me.Refresh before those fields' new values are accessible. Hopefully someone with more specific experience will correct me if I am wrong. I think something like this should work for you:
Me.Refresh
Pause1 = DateDiff("s", Me.tsPause1, Me.tsResume1)
Pause2 = DateDiff("s", Me.tsPause2, Me.tsResume2)
ECTime = (DateDiff("s", Me.tsECStart, Me.tsUpdated) - (Pause1 + Pause2))
LTime = DateDiff("s", Me.tsStartAll, Me.tsEndAll)

Related

Data type miss match in criteria exxpression access

I am going to VBA for deleting data table.
It shows the errors shown in the screenshot.
Please help me to resolve it.
Private Sub cmdxoa_Click()
If Not (Me.frmformsub1.Form.Recordset.EOF And Me.frmformsub1.Form.Recordset.BOF) Then
If MsgBox("Do you wwant to delete ?", vbYesNo) = vbYes Then
CurrentDb.Execute "DELETE from db " & _
" where NOLC = " & Me.frmformsub1.Form.Recordset.Fields("nolc")
Me.frmformsub1.Form.Requery
End If
End If
End Sub
So if NOLC in the table is of type text, your criteria expression has to be:
"where NOLC = '" & Me.frmformsub1.Form.Recordset.Fields("nolc").Value & "'"
As you see you have to surround the value with '.
Remark: .Value isn't necessary, but it enhances the readability and assures that you are interested in the value and not in the object itself (the control in that case).
BUT: You should use parametrized queries instead string concatenation to avoid SQL injection:
How do I use parameters in VBA in the different contexts in Microsoft Access?

Why this statement cannot be updated in the database

I am facing this issue with my query. I would like you to kindly help me resolve it.
MD = "UPDATE librarysystem.audit set timeout = '" & Today + "" + TimeOfDay & "' AND status='0' WHERE username = '" & AccountId & "'AND status = '1'"
cmd = New MySqlCommand(MD, con)
cmd.ExecuteNonQuery()
here's the code:
connect()
Dim result As Integer = MessageBox.Show("Are You Sure You Want To LOGOUT?", "Are You?", MessageBoxButtons.YesNo)
If result = DialogResult.No Then
Me.Show()
ElseIf result = DialogResult.Yes Then
connect()
Dim time As DateTime
time = Date.Today
Dim a As Integer = 0
MD = "UPDATE librarysystem.audit set timeout = '" & Today + "" + TimeOfDay & "' AND status='0' WHERE username = '" & AccountId & "'AND status = '1'"
cmd = New MySqlCommand(MD, con)
cmd.ExecuteNonQuery()
AccountSettings.Hide()
BorrowedBooks.Hide()
LogHistory.Hide()
Login.Hide()
ReturnedBooks.Hide()
SearchBooks.Hide()
End If
End Sub
:
Thank you in advance ^^
One of the deep hassles of SQL is that you're usually embedding one language in another. That makes it hard to read things in both languages clearly. Here's your SQL extracted from your vb.
UPDATE librarysystem.audit
set timeout = '" & Today + "" + TimeOfDay & "'
AND status='0'
WHERE username = '" & AccountId & "'AND status = '1'"
Here it is with some sample values substituted
UPDATE librarysystem.audit
set timeout = '2016-11-26 13:14:15'
AND status='0'
WHERE username = 'SomeUserName'AND status = '1'
You should be able to carry out that statement directly on your dbms and have it function correctly. But, look it over. What do you see?
I see an AND where there should be a , in the list of columns to update. AND only works in WHERE and ON clauses, not in lists of columns.
I see a missing space in the SQL in the sequence 'SomeUserName'AND.
I also see some potential confusion in the way your vb program created the value for timeout. It's not immediately clear whether your vb TimeOfDay variable will render in 24h format (13:14:15) or in am/pm format (01:14:15 PM).
Finally, I see an extraordinarily common mistake. The SQL statement is jammed onto one line, as if it had been written in the 1980s by a psychotic APL programmer. This makes your language-in-a-language program almost impossible to read.

How to use "INSERT INTO" command from Access VBA to Sharepoint

I'm using a MS Access database linked with a Sharepoint Server. MS Access Forms as FrontEnd and Sharepoint Lists as BackEnd.
Today i can see all the informations from the lists using access forms, without problems.
What i need:
I'm trying to insert new registers on the list, using a SQL command: "INSERT INTO..."
if there is another possibility to insert the record in the list, may be useful
What's happening?
When i call the DoCmd.RunSQL(txtsql), i receive a runtime error 3999 saying i'm disconnected from the server.
My code now:
I tried using recordsets, but didn't succeed.
I need to run this SQL many times, changing the string "txtSql" inside a loop. Like this:
Dim MaxSonda As Integer
'Get the max ID from the list
MaxSonda = Nz(DMax("IdSonda", "Sondas", "((Sondas.[Tipo Sonda])<>1 Or (Sondas.[Tipo Sonda]) Is Null)"), 0)
MsgBox "MaxSonda = " & MaxSonda
'Run the code for each "sonda"
Do While MaxSonda > 1
If Nz(DLookup("[Tipo Sonda]", "Sondas", "Sondas!IdSonda = " & MaxSonda), 1) <> 1 Then
DoCmd.OpenTable "Resumo", acViewNormal, acAdd
DoCmd.GoToRecord acDataTable, "Resumo", acNewRec
txtSql = "INSERT INTO Resumo ( Data, Sonda, Status ) SELECT #" & LastData + 1 & "#, " & MaxSonda & ", 0;"
MsgBox txtSql
DoCmd.RunSQL txtSql
DoCmd.Close acTable, "Resumo", acSaveYes
End If
MaxSonda = MaxSonda - 1
Loop
P.S.: The MsgBox is just for check the steps
thanks for help
You don't need to open the list/table to insert a record. I don't know why you are using loop to insert rows but if that is your intention try this SQL_COMMAND within your loop:
If Nz(DLookup("[Tipo Sonda]", "Sondas", "[IdSonda] = " & MaxSonda), 1) <> 1 Then
txtSql = "INSERT INTO Resumo ( Data, Sonda, Status ) VALUES ('" & LastData + 1 & "'," & MaxSonda & ",0);"
MsgBox txtSql
DoCmd.RunSQL txtSql
End If
also note #tags are used to insert dates in Access, if you are intend to save dates save them in international format as strings like
vba.Format$([date_field],"yyyy-mm-dd hh:mm:ss")
this way you can just save as string without using the #tags.
Maybe this could help somebody. I did have the same problem and i solved it removing the sharepoint list from access and add it again. Take a seconds to make a sql query but it works.
greet

Access type mismatch on date field with SQL Server express backend

I have a simple access form with an unbound textbox that is used to search for records with a matching date, with the results displayed in a subform. The backend database is stored in an SQL Express 2008 instance, accessed via an ODBC connection (SQL Server Native Client 10.0). The client is Access 2007, running on 64 bit Windows 7 professional.
When the user clicks on the search button on the form, the following VBA code is executed to update the subform.
Private Sub UpdateSfmQuery()
Dim query As String
If IsDate(txtDate.Value) And IsNumeric(cboStaff.Value) Then
query = "SELECT * FROM TimesheetEntries " & _
"WHERE StaffId = " & cboStaff.Value & " " & _
"AND [Date] = '" & _
Format(txtDate.Value, "YYYY/MM/DD HH:MM:SS") & "' "
Else
query = "SELECT * FROM TimesheetEntries WHERE 0 = 1;"
End If
frmTimesheetUpdateSfm.Form.RecordSource = query '<--- Fails here
End Sub
The datatype in the SQL Server back end [Date] field is DateTime, and the code above fails on the highlighted line above with the error, Data type mismatch in criteria expression.
I've tried changing the format property of txtDate from short date to general date, and I've also modified the date format in the line above that formats txtDate.Value.
The SQL query contained in the variable query in the above code excerpt (value shown below), executes perfectly when copied and pasted into SQL Express Management Studio.
SELECT * FROM TimesheetEntries WHERE StaffId = 14 AND [Date] = '2011/11/22 00:00:00'
What am I doing wrong?
The problem is that date values inside native Access queries need to be surrounded by pound/hash signs instead of quotes. Basically, like any SQL database, Access has it's own dialect of SQL and it is slightly different from SQL Server.
Private Sub UpdateSfmQuery()
Dim query As String
If IsDate(txtDate.Value) And IsNumeric(cboStaff.Value) Then
query = "SELECT * FROM TimesheetEntries " & _
"WHERE StaffId = " & cboStaff.Value & " " & _
"AND [Date] = #" & _
Format(txtDate.Value, "YYYY/MM/DD HH:MM:SS") & "# "
Else
query = "SELECT * FROM TimesheetEntries WHERE 0 = 1;"
End If
frmTimesheetUpdateSfm.Form.RecordSource = query '<--- Used to fail here
End Sub
Remember, you can always take a mockup of your query and use Access's query editor to try to make the query work.
As a side note, I recommend you tag questions like this with the ms-access tag unless your problem is specific to a certain version of Access.

How can I check for null values in Access?

I am new to Access. I have a table full of records. I want to write a function to check if any id is null or empty. If so, I want to update it with xxxxx.
The check for id must be run through all tables in a database.
Can anyone provide some sample code?
I'm not sure if you are going to be able to find all tables in the database with Access SQL. Instead, you might want to write up some VBA to loop through the tables and generate some SQL for each table. Something along the lines of:
update TABLE set FIELD = 'xxxxxx' where ID is null
Check out the Nz() function. It leaves fields unaltered unless they're null, when it replaces them by whatever you specify.
For reasonable numbers and sizes of tables, it can be quicker to just
open them
sort by each field in turn
inspect for null values and replace manually
It's good practice to find out where the nulls are coming from and stop them - give fields default values, use Nz() on inputs. And have your code handle any nulls that slip through the net.
I'm calling it the UpdateFieldWhereNull Function, and shown is a Subroutine which calls it (adapted from http://www.aislebyaisle.com/access/vba_backend_code.htm)
It updates all tables in the DbPath parameter (not tested, handle with care):
Function UpdateFieldWhereNull(DbPath As String, fieldName as String, newFieldValue as String) As Boolean
'This links to all the tables that reside in DbPath,
' whether or not they already reside in this database.
'This works when linking to an Access .mdb file, not to ODBC.
'This keeps the same table name on the front end as on the back end.
Dim rs As Recordset
On Error Resume Next
'get tables in back end database
Set rs = CurrentDb.OpenRecordset("SELECT Name " & _
"FROM MSysObjects IN '" & DbPath & "' " & _
"WHERE Type=1 AND Flags=0")
If Err <> 0 Then Exit Function
'update field in tables
While Not rs.EOF
If DbPath <> Nz(DLookup("Database", "MSysObjects", "Name='" & rs!Name & "' And Type=6")) Then
'UPDATE the field with new value if null
DoCmd.RunSQL "UPDATE " & acTable & " SET [" & fieldName & "] = '" & newFieldValue & "' WHERE [" & fieldName & "] IS NULL"
End If
rs.MoveNext
Wend
rs.Close
UpdateFieldWhereNull = True
End Function
Sub CallUpdateFieldWhereNull()
Dim Result As Boolean
'Sample call:
Result = UpdateFieldWhereNull("C:\Program Files\Microsoft Office\Office\Samples\Northwind.mdb", "ID", "xxxxxx")
Debug.Print Result
End Sub