Write username to a table from a form - ms-access

I am trying to write the user name who is currently logged in to records in the table X that is used to update table Y with new records from it.
Here is the code I use:
Private Sub UPD_Click()
On Error GoTo Err_UPD_Click
DoCmd.TransferDatabase acImport, "Microsoft Access", "D:\Working\Test.mdb", acTable, "tblTest", "tblTest_Import", False
DoCmd.RunSQL "ALTER TABLE tblTest_Import ADD COLUMN [CreatedBy] Text(25);"
Dim myDB As Database
Set myDB = CurrentDb
myDB.Execute "UPDATE tblTest_Import " _
& "SET [tblTest_Import].[CreatedBy] = [Forms]![frmLogin]![txtUserName];"
myDB.Execute "INSERT INTO tblMain(Year, CreatedBy)"_
& "SELECT tblTest_Import.Year, tblTest_Import.CreatedBy " _
& "FROM tblTest_Import " _
& "WHERE (((Exists (SELECT * FROM tblMain " _
& "WHERE tblMain.ID = tblTest_Import.ID))=False));"
Exit_UPD_Click:
Exit Sub
Err_UPD_Click:
MsgBox Err.Description
Resume Exit_UPD_Click
End Sub
Form frmLogin stays open but hidden (Me.Visible = False).
The problem is the field CreatedBy in tblTest_Import does not get updates and Access returns this message: "Too few parameters. Expected 1." And none of lines in the code gets highlighted.
I tried to add
Dim frmLogin As Form
Set frmLogin = Screen.ActiveForm
but it didn't help.
What is wrong with my code?

I found solution :)
I just needed to add several quotes to this part of code
myDB.Execute "UPDATE tblTest_Import " _
& "SET [tblTest_Import].[CreatedBy] = '" & [Forms]![frmLogin]![UserName] & "';"
Bingo!

Related

Access Database closes upon closing Word document following data export

I have a database which stores customer job data. This data is also used to print certificates for the customer via export to an existing word document. The database is quite old and works fine on office 2003. Upon upgrading to latest office 365 I now have an issue whereby after I export the data to Word, I cannot close Word without Access also closing. I then have to re-open Access to continue using the database. Hoping somebody knows how to stop this happening.
The data is exported to Word at the click of a button in a form and the VBA code it runs is listed below. (I did not create the code or the database)
Thanks in advance
Private Sub btnPrintCert_Click()
On Error GoTo Err_btnPrintCert_Click
Dim strSQL As String
Dim RetVal As Double
Dim txtWordPath As String
Dim txtDocPath As String
Dim txtShellCommand As String
If Me.Dirty Then
RunCommand acCmdSaveRecord
End If
' delete temporary table
DoCmd.DeleteObject acTable, "tbltemp_cert"
' build sql string
strSQL = "SELECT qryjobs.postal, qryjobs.payload, qryjobs.JobNumberFull, qryjobs.job_said, qryjobs.job_entrydate, qryjobs.job_number, qryjobs.job_description, qryjobs.job_required_by, qryjobs.job_client_ordernumber, "
strSQL = strSQL & "qryjobs.job_complete_date, qryjobs.job_completed, qryjobs.cert_owner, qryjobs.cert_address, qryjobs.cert_vehicleyear, qryjobs.cert_vehiclemake, qryjobs.cert_vehiclemodel, qryjobs.cert_chassis, "
strSQL = strSQL & "qryjobs.cert_vin, qryjobs.cert_rego, qryjobs.cert_axles, qryjobs.cert_application, qryjobs.cert_hubo, qryjobs.cert_huboserial, qryjobs.cert_readingdate, qryjobs.cert_hubo_expiry_km, "
strSQL = strSQL & "qryjobs.cert_fleetnumber, qryjobs.cert_tare, qryjobs.cert_GVM, qryjobs.cert_GCM, qryjobs.cert_period, qryjobs.cert_expires, qryjobs.cert_MTM_braked, qryjobs.cert_MTM_unbraked, "
strSQL = strSQL & "qryjobs.cert_front_axlerating, qryjobs.cert_rear_axlerating, qryjobs.cert_axle_spacings, qryjobs.cert_VSR_class, qryjobs.company, qryjobs.addr1line1, qryjobs.addr1line2, qryjobs.addr1line3, "
strSQL = strSQL & "qryjobs.addr1line4, qryjobs.addr1city, qryjobs.addr1state, qryjobs.addr1postcode, qryjobs.addr2line1, qryjobs.addr2line2, qryjobs.addr2line3, qryjobs.addr2line4, qryjobs.addr2city, qryjobs.addr2state, "
strSQL = strSQL & "qryjobs.addr2postcode, qryjobs.phone1, qryjobs.phone2, qryjobs.fax, qryjobs.identifier, qryjobs.salutation, qryjobs.contactname, qryjobs.notes, qryjobs.company_type, qryjobs.job_type_desc, "
strSQL = strSQL & "qryjobs.job_type_code, qryjobs.job_type_LTSA_appr_code, qryjobs.job_type_designcode, qryjobs.job_type_cert_text, qryjobs.job_cert_word_doc, qryjobs.job_type2_desc, qryjobs.job_type2_code, "
strSQL = strSQL & "qryjobs.job_type2_title, qryjobs.VSR_class, qryjobs.VSR_class_description, qryjobs.axle_description, qryjobs.vehicle_make, qryjobs.application_description, qryjobs.expired_now, qryjobs.cert_vertical_rating, qryjobs.vert_rating, "
strSQL = strSQL & "qryjobs.qrywelders_all.Name, qryjobs.qrywelders_all.Employer, qryjobs.qrywelders_all.[4711No], qryjobs.qrywelders_all.Positions, qryjobs.qrywelders_all.Expires "
strSQL = strSQL & "INTO tbltemp_cert FROM qryjobs WHERE [qryjobs.job_said] =" & Me!job_said & ";"
' write current record info to temp table
DoCmd.RunSQL strSQL
' open & display selected word document according to job type
' the Shell function runs an executable program and returns a
' Variant (Double) representing the program's task ID if successful,
' otherwise it returns zero.
txtWordPath = "C:\Program Files\Microsoft Office\root\Office16\Winword.exe"
txtDocPath = Me![job_cert_word_doc]
txtShellCommand = Chr(34) & txtWordPath & Chr(34) & " " & Chr(34) & txtDocPath & Chr(34)
Debug.Print "shellcommand: " & txtShellCommand
RetVal = Shell(txtShellCommand, 1)
Exit_btnPrintCert_Click:
Exit Sub
Err_btnPrintCert_Click:
MsgBox Err.Description
Resume Exit_btnPrintCert_Click
End Sub

Run-time error '2498' - Access 2010 VBA - DoCmd.TransferSpreadsheet

I am writing a script that filters a query based off user input, then data in this query will be used to make a new table qryMyExportedData. From there, the data will be exported to ExportedData.xlsx. When I attempt to run my code, I get the following error:
Run-time error '2498': An expression you entered is the wrong data type for one of the arguments.
My code:
Private Sub Query_Click()
Dim strExport as String
strExport = "SELECT * FROM qryCostDepLosses WHERE [Maintenance Type] = '" & Me.MainType & "' AND [Date] = #" & Me.Date & "#"
Set qdfNew = CurrentDb.CreateQueryDef("myExportQueryDef", strExport)
DoCmd.TransferSpreadsheet acExport, acSpreadsheetTypeExcel12, "myExportQueryDef", CurrentProject.Path & "\ExportedData.xlsx", "True"
CurrentDb.QueryDefs.Delete qdfNew.Name 'cleanup
End Sub
I have narrowed down the error to the DoCmd.TransferSpreadsheet line. The strExport looks as it should, I believe. The data is exported to myExportQueryDef as well.
Your are attempting to send a Boolean as a String. So the code should look like this:
Private Sub Query_Click()
Dim strExport as String
strExport = "SELECT * FROM qryCostDepLosses WHERE [Maintenance Type] = '" & Me.MainType & "' AND [Date] = #" & Me.Date & "#"
Set qdfNew = CurrentDb.CreateQueryDef("myExportQueryDef", strExport)
DoCmd.TransferSpreadsheet acExport, acSpreadsheetTypeExcel12, "myExportQueryDef", CurrentProject.Path & "\ExportedData.xlsx", True
CurrentDb.QueryDefs.Delete qdfNew.Name 'cleanup
End Sub
Basically just remove the quotes from around True.

On updating shows message: Save or drop changes or copy to clipboard

I was asked to capture the date when a specific field is updated , so I created an event to update the record of that field.
Dim db As Database
Dim strSQL As String
Dim LDate As String
LDate = Format(Date, "yyyy-mm-dd")
Set db = CurrentDb
strSQL = "UPDATE [Lotinfo] " & _
"SET [PriorityChanged] = " & _
Chr(34) & LDate & Chr(34) & _
" where [BKPO#] = " & _
Chr(34) & Forms![LotTabFrm]![LotInfoPriority]![BKPO#] & Chr(34) & _
" and [ModelNo] = " & _
Chr(34) & Forms![LotTabFrm]![LotInfoPriority]![ModelNo] & Chr(34)
DoCmd.SetWarnings False
DoCmd.RunSQL strSQL
DoCmd.SetWarnings True
The update does happen, however it keeps showing a 'copy to clipboard' message box asking me to drop the changes or copy to clipboard and in both cases the changes are lost
Is there a way to stop that message box from showing up?
You are getting this message because Ms Access has a conflict. Should it save the values you entered into the form or rather the values you are entering now using the UPDATE statement?
Assuming that you want the values from the UPDATE statement, add the following line before the UPDATE to save the Form values first:
DoCmd.RunCommand acCmdSaveRecord

Access VBA to update Access table from SQL Server table source

I have created the code below to test whether I can run a query and retrieve a data from an SQL server table. And so far I can return the result using a MessageBox, but somehow I just don't know how to use this connection to update the table inside this Access file. Basically I want to use this as a front end file. Then, when the form is open it will automatically update the table inside this access file and load the data to the combo box as a list. I tried searching it here and read many discussions here and in Google but currently I can't find the right solution.
Option Compare Database
Sub LocalServerConn_Test()
Set conn = New adodb.Connection
Set rst = New adodb.Recordset
strDBName = "DataSet"
strConnectString = "Provider = SQLOLEDB.1; Integrated Security = SSPI; " & _
"Initial Catalog = " & strDBName & "; Persist Security Info = True; " & _
"Worksation ID = abc123;"
conn.ConnectionString = strConnectString
conn.Open
strSQL = "SELECT DISTINCT dbo.abc.abc123 FROM dbo.abc"
rst.Open Source:=strSQL, ActiveConnection:=strConnectString, _
CursorType:=adOpenDynamic, LockType:=adLockOptimistic
If rst.RecordCount = 0 Then
MsgBox "No records returned"
Else
rst.MoveFirst
Do While Not rst.EOF
MsgBox rst.Fields("abc123").Value
rst.MoveNext
Loop
End If
conn.Close
rst.Close
End Sub
You should be able to use code very similar to this:
Dim cdb As DAO.Database
Set cdb = CurrentDb
cdb.Execute _
"DELETE FROM LocalTable", _
dbFailOnError
cdb.Execute _
"INSERT INTO LocalTable (abc123) " & _
"SELECT DISTINCT abc123 " & _
"FROM " & _
"[" & _
"ODBC;" & _
"Driver={SQL Server};" & _
"Server=.\SQLEXPRESS;" & _
"Database=DataSet;" & _
"Trusted_Connection=yes;" & _
"].[dbo.abc]", _
dbFailOnError
Set cdb = Nothing
You can just keep the combo box bound to [LocalTable] and the updated values from the SQL Server table should appear.

how to update a mainform into a subform

After I edit information and change the information and click update, it gives me a error. I tried the parenthesis brackets no luck.
Too few parameters Expected 1. Run time error '3061'
Private Sub cmdUpdate_Click()
Dim strSql As String
strSql = "UPDATE PlantTransaction " & _
"SET TransactionID=" & Me.txtTranID & _
",[Plant Number]='" & Me.txtPlantNo & "'" & _
",TransactionDate=#" & Me.txtTransDate & "#" & _
",Opening_Hours='" & Me.txtOpeningHRS & "'" & _
",Closing_Hours='" & Me.CloseHrs & "'" & _
",Fuel='" & Me.txtFuel & "'" & _
",[Fuel Cons Fuel/Hours]='" & Me.txtFuelConsFuelHr & "'" & _
",[Hour Meter Replaced]='" & Me.txtHrMtrRep & "'" & _
",Comments='" & Me.txtComments & "'" & _
",[Take on Hour]='" & Me.txtTOH & "'" & _
" WHERE TransactionID=" & Me.PlantTransactionQuery.Form.Recordset.Fields("Tr ansactionID")
Debug.Print strSql ' <- prints to Immediate window
CurrentDb.Execute strSql, dbFailOnError
cmdClear_Click
Me.PlantTransactionQuery.Form.Requery
End Sub
You were smart to include this line in your code:
Debug.Print strSql ' <- prints to Immediate window
Now when you get the missing parameter message, go to the Immediate window (you can use Ctrl+g to go there) and copy the SQL statement.
Then create a new Access query in the query designer, switch to SQL View, and paste in the text you copied. When you attempt to run that query, Access will present a parameter input box which includes the name of whatever it thinks is the parameter.
Compare that parameter name with the field names in your data source. Often this situation occurs because the query includes a misspelled field name. Another possibility with an UPDATE is that one of the values you're trying to update is unquoted text. Regardless of the cause, the parameter name from that input box should help you track it down. Show us the actual text from that UPDATE statement if you need further help.
Any time that you "glue together" a long SQL statement with lots of user input you face the challenges of
correctly delimiting strings and dates,
escaping delimiters within such fields (usually quotes inside a text field), and
getting all of the required commas in the right places
You can avoid those annoyances by using a Recordset to perform the update:
Dim rst As DAO.RecordSet
Set rst = CurrentDb.OpenRecordset("PlantTransaction", dbOpenDynaset)
rst.FindFirst "TransactionID=" & Me.PlantTransactionQuery.Form.Recordset.Fields("Tr ansactionID")
If Not rst.NoMatch Then
rst.Edit
rst!TransactionID = Me.txtTranID
rst![Plant Number] = Me.txtPlantNo
rst!TransactionDate = Me.txtTransDate
rst!Opening_Hours = Me.txtOpeningHRS
rst!Closing_Hours = Me.CloseHrs
rst!Fuel = Me.txtFuel
rst![Fuel Cons Fuel/Hours] = Me.txtFuelConsFuelHr
rst![Hour Meter Replaced] = Me.txtHrMtrRep
rst!Comments = Me.txtComments
rst![Take on Hour] = Me.txtTOH
rst.Update
End If
rst.Close
Set rst = Nothing