Pulling information to unbound fields - mysql

I am trying to pull data from an unlinked table to a form with unbound fields. I already have a form where you enter the data and send it to the table but this is to be able to pull it back and update.
This is what I have
DoCmd.RunSQL "SELECT * " & _
" FROM [" & Address & "].[BusinessAccountOpening]" & _
" WHERE [ID]= " & Me![txtID] & ""
Forms!frm_ViewUpdateRecords!Sub_Details.Form.subaddthedata
But getting the error. An RunSQL action requires an argument consisting of an sql statement.
Please help

DoCmd.RunSQL and CurrentDb.Execute are for action queries (delete, update, append) while you present a select query.
So call DoCmd.OpenQuery ... or assign the records to a recordset.

Related

Access add new line to table

I have sub that runs when the database is opened to a specific form and I'm trying to get it to add information in a table.
The table name is UnAuthorizedAccess and the columns in table are ID(auto number), NAME(text), COMPUTERNAME(text), ATTEMPTDATE(date/time).
What commands do I need to use to add a new record to this table? I have a VBA that if they're login information Isn't there is will force close access all together. I'm trying to gather information on the user as well before kicking them out.
I figured this is the easiest way as outlook won't let you send a hidden email from the user unless they first see it.
You can add records to a recordset with the following code, but I am unsure whether you have a field called COMPUTERNAME. You shouldn't need to add the ID value as its an autonumber.
dim Rst as recordset
Set Rst = CurrentDb.OpenRecordset(Name:="UnauthorizedAccess", Type:=RecordsetTypeEnum.dbOpenDynaset)
With Rst
.AddNew
![NAME] = Me.Name.Value
![COMPUTERNAME] = Me.COMPUTERNAME.Value
![ATEMPTDATE] = date()
.Update
End With
As for sending hidden emails, see this question I asked not so long ago. It sends an email via outlook, but remember to reference the Microsoft Outlook Object library in the VBA Editor.
CurrentDB.Execute is the method for executing SQL statements, and INSERT INTO is the SQL statement for adding records to a DB table.
CurrentDB.Execute "INSERT INTO UnAuthorizedAccess (NAME, COMPUTERNAME, ATTEMPTDATE) " & _
"VALUES (" & Your_NAME_Variable & ", " & Your_COMPUTERNAME_Variable & ", " & Now() & ")
Replace Your_NAME_Variable and Your_COMPUTERNAME_Variable with the variables in your code containing these values.

MS Access 2013 copy a specific number of fields and paste into a new record

I have found similar answers to this question, even on this site, however, the syntax has not worked for my database and I'm not sure what needs to be done. This data base is used to house audits for staff performance and accuracy. I am now in the midst of creating the forms and getting them to flow properly for the user.
When conducting an audit, the user will need to enter six specific fields into the first form. Those forms are Audit, Month, Year, Username, Location, Reviewer, and Date. The user will need to complete multiple audits, however, these six fields will always be the same.
I would like to copy these fields in the first form and carry them into the second form so the user does not have to repeat the information. Here is my current code (set to run on the click of a command button on the bottom of screen 1):
Dim strSQL As String
strSQL = "INSERT INTO [tblTripMem] (Audit, Month, Year, Username, Location, Reviewer, Date)"
strSQL = strSQL & " Values (" & Me.cboFP1Audit & "," & Me.Month & "," & Me.Year & "," & Me.Username & "," & Me.Location & "," & Me.Reviewer & "," & Me.Date & ") FROM [FPScreen1]"
strSQL = strSQL & "WHERE (currentrecord = " & Me.CurrentRecord & ")"
DoCmd.RunSQL (strSQL)
Each time I run this I receive the following error: "Invalid SQL statement; expected 'DELETE', 'INSERT', 'PROCEDURE', 'SELECT', or 'UPDATE'.
I am new to Access and am unsure of what this means or how to fix it. All I know is that I'm not finding a solution. Can anyone help? I'd greatly appreciate it.
Here's a mock-up Access file illustrating a way to do what you're doing without using SQL:
With Form 1 open...
...complete the various fields:
Click the Copy to Form 2 button and this will open Form 2 and populate its fields with the data from Form 1:
Here's the VBA code on the Copy to Form 2 button's OnClick event:
Private Sub cmdCopyToFrm2_Click()
Dim frm As Form
DoCmd.OpenForm "Form2"
Set frm = Forms!Form2
With frm
!AuditRef = Me.cboFP1Audit
!AuditMonth = Me.txtAuditMonth
!AuditYear = Me.txtAuditYear
!AuditUsername = Me.txtAuditUsername
!Location = Me.txtLocation
!Reviewer = Me.txtReviewer
!AuditDate = Me.txtAuditDate
End With
End Sub
Note that when Form 2 opens, the textbox that the cursor defaults to might not seem to show any data; if you move away from that textbox it should magically show (don't know why it does this, but there you go).
INSERT INTO table (...) VALUES (...) cannot have a FROM or WHERE clause. You insert a single record with fixed values, not data from another table.
But once you delete these clauses, you will have other errors, because you need to format your string and date values correctly to get the INSERT query to work.
And then you will still be prone to SQL injection errors. It is safer to use Recordset.AddNew and .Update to add records.
See e.g. here: https://stackoverflow.com/a/34969410/3820271
(but without the loop)

Why are duplicate records being generated in the table?

I am using MS Access 2010. I have a form that captures a couple data items and then writes the record to a table using a function that I defined. The function is called in the click event of the Write Record command-button in the form.
Form:
Code:
> Private Sub writerecord_Click()
Rem MsgBox ("in write record click event")
Dim sqlString As String
Rem 1 - write to the kit_items table
sqlString = "INSERT INTO kit_items (item_vendorid, item_name, item_description, item_cost) VALUES (" & Me!vendorlist & ", '" & Me!item_name & "', '" & Me!item_description & "', '" & Me!item_cost & "');"
DoCmd.RunSQL sqlString
MsgBox ("done writing to table kit_items")
End Sub
records saved in table looks like this
**What is generating the duplicate record ?
If your form is bound to the table that you are writing to, the button will add a second record.
If you would like to work with data this way, you would need to make sure that the form is unbound.
Beware however that if you don't take steps to 'clear' out the data once the user clicks the button to write the record, every time they click the button you will get a new record.
Is there some reason why you need to do the inserting manually (as opposed to letting the bound form handle the inserts/edits)?

Access Table updating another Access Table based on variable fields

I think my first submission might have been a bit confusing so I decided to rewrite it to better explain what I am attempting to do.
I have an Access database. In it there are two combo boxes, one containing all possible forms of annuity (that I'm dealing with) and the other combo box is the ones the user populates that apply to that particular client. This master list is fed from a table (tblPickAnnuityForms). This table has 3 fields, Name, VarName (these values match to another table), and Deleted (is a 1 or a 0 depending on if the user selected it). I also have a second table called tblPlanSpecs. This table, among other fields, has the fields that match up to the VarName field in the first table.
What I need to do, since tblPickAnnuityForms is basically a temporary table and it changes as you move between records (clients), is to repopulate it when you go to that record based on the values in tblPlanSpecs. Once tblPickAnnuityForms is populated based on the previous elections for this record (client), the two combo boxes are re-queried to display the proper values (ie the left box shows the remaining, unused annuity forms and the right box shows the forms that apply to this client.
Below is my attempt at doing this.
Dim db As DAO.Database
Dim rsList As DAO.Recordset
Dim rsData As DAO.Recordset
Dim CurrForm As String
Dim FormVal As Integer
Dim Plan As String
Set db = CurrentDb
Set rsList = db.OpenRecordset("tblPickAnnuityForms", dbOpenSnapshot)
Plan = [Forms]![FrmHome]![PlanNameCalc].Value
Set rsData = db.OpenRecordset("SELECT tblPlanSpecs.LifeAnnuity, tblPlanSpecs.FiveCC, tblPlanSpecs.TenCC, " _
& "tblPlanSpecs.FifteenCC, tblPlanSpecs.TwentyCC, tblPlanSpecs.FiveCertain, tblPlanSpecs.TenCertain, " _
& "tblPlanSpecs.FifteenCertain, tblPlanSpecs.TwentyCertain, tblPlanSpecs.FiftyJS, tblPlanSpecs.SixtySixJS, " _
& "tblPlanSpecs.SeventyFiveJS, tblPlanSpecs.HundredJS, tblPlanSpecs.MCR FROM tblPlanSpecs " _
& "WHERE tblPlanSpecs.PlanName='" & Plan & "'")
Do
CurrForm = rsList.Fields("VarName")
FormVal = rsData.Fields(CurrForm)
DoCmd.RunSQL ("UPDATE tblPickAnnuityForms " _
& "SET tblPickAnnuityForms.Deleted=" & rsData! & FormVal & " " _
& "WHERE (((tblPickAnnuityForms.VarName)='" & CurrForm & "'))")
MsgBox (CurrForm & "changed to " & FormVal)
rsList.MoveNext
Loop Until rsList.EOF
If Not rsList Is Nothing Then
rsList.CLOSE
Set rsList = Nothing
End If
If there is a better solution, perhaps I can go in a different direction. Currently this is bombing out in the loop where it says rsData! & FormVal It does not like using a variable to call a field. Ideally I would like to avoid specifically calling every variable by name in code when populating rsData. In other words, I want this to work no matter how many other options I add to my master list for the combo box, without going back in to add more items to select query.
Please let me know if I am unclear in my intended direction or methods. I could really use the help figuring out what is wrong.
Well, it seems I solved my own problem. I had so many ideas running through my head, I half-implemented one and forgot. The variable FormVal was already pulling the value I needed from rsData. I then tried to pull the value again using FormVal as the field variable. Anyway, below was the simple solution and everything works now.
DoCmd.RunSQL ("UPDATE tblPickAnnuityForms " _
& "SET tblPickAnnuityForms.Deleted=" & FormVal & " " _
& "WHERE (((tblPickAnnuityForms.VarName)='" & CurrForm & "'))")
In other words, I didn't need to do rsData![ & FormVal & ] (which I am sure is improper syntax) I just needed to use FormVal by itself.

Error 3622 - You must use the dbSeeChanges option with OpenRecordset when accessing a SQL Server table that has an IDENTITY column

I'm running MS Access 2007, connecting to a MS SQL 2008 R2 server. I have a form with a multiselect box that I use to update status for several fields for the servers selected. Currently I'm using the ServerName field in the multiselect box. The problem is that there can be multiple records with the same server name. So to get around this I want to change it from ServerName to record number (ID). When I do this though VB gives the error "Error 3622 - You must use the dbSeeChanges option with OpenRecordset when accessing a SQL Server table that has an IDENTITY column". I've looked at many different posts on different websites, but can't figure out how to implement this into my code. The script works perfectly when I use ServerName, it also works perfectly if I go to the SQL server and change the field to Identity = False. The problem with that is that I can't create new records with the autonumber. It also works perfectly if I hard code the line numbers in an Update query. The problem with that is I can't hardcode the line numbers for everyone that uses the database. The issue only appears to be related to VB.
Below is what I have currently. As you can see I tried adding the dbSeeChanges to the Execute line.
Private Sub btnRoarsStatus_Click()
Dim strSQL As String
Dim Criteria As String
Dim Itm As Variant
With Me.lstServerNames
If .ItemsSelected.Count > 0 Then
For Each Itm In .ItemsSelected
Criteria = Criteria & "," & .ItemData(Itm)
Next Itm
' remove leading comma
Criteria = Mid(Criteria, 2)
' execute the SQL statement
strSQL = "UPDATE buildsheet SET [Roars Status] = " & Chr(34) & _
Me.cboRoarsStatus & Chr(34) & " WHERE ID IN(" & Criteria & ")"
Debug.Print strSQL
CurrentDb().Execute strSQL, dbSeeChanges
Else
MsgBox "You must select one or more items in the list box!", _
vbExclamation, "No Selection Made"
Exit Sub
End If
End With
MsgBox "Completed", vbExclamation, "Completed"
End Sub
I had a similar Problem with a Delete Statement that I wanted to execute and solved it by:
CurrentDb.Execute SqlStr, dbSeeChanges
note the missing () after CurrentDb
For me worked this:
CurrentDb.Execute strSQL, **dbFailOnError +** dbSeeChanges
dbFailOnError was the key...
CurrentDb().Execute strSQL, someotherConstant, dbSeeChanges
I think, someotherConstant maybe missing.