Insert data from a form into a table [duplicate] - vba

This question already has an answer here:
Inserting data from a form into a table
(1 answer)
Closed 7 years ago.
It's been probably 3 years since I have had to use VB or VBA code. I am working on a project for work using Microsoft Access where I need to take the information that is listed on the form and insert it into a table. What I am stuck on is the last part of the code the values part. This is what I have so far.
INSERT Volunteers (Name, Email, Number, Emergency Contact, Emergency Number) VALUES (and this is where I get stuck)
Thank you all in advance!

You want the single-record table append query:
INSERT INTO Volunteers (Name, Email, Number, Emergency Contact, Emergency Number)
VALUES ("Value1", "Value2", "Value3", "Value4", "Value5")
Assuming you are constructing the SQL statement in the code-behind of the form, you can access the controls by name:
Dim sql As String
sql = _
"INSERT INTO Volunteers (Name, Email, Number, Emergency Contact, Emergency Number) " & _
"VALUES (""" & txbName & """, """ & txbEmail & """, """ & txbNumber & """, """ & txbEmergencyContact & """, """ & txbEmergencyNumber & ")"
(All those triple-quotes are to get a double-quote (") into the final SQL statement, for text fields; numeric fields don't need any delimiter, and date fields use the # as a delimiter.)
If you are adding values from a different form, you can access them like so:
Forms!OtherForm!ControlName
and values in a subform (IIRC):
SubformControl.Form!ControlName
See here for more details.

Related

MS Access / SQL : error in insert query statement

I am using MS Access 1997 version (.mdb file). On a daily basis, I need to insert values manually. In that file, there's a column Logical (Boolean data type). I am automate this template using SQL query instead of direct entry.
Below is my insert query:
Insert Into Data_CustomerTransmit_Tbl (Logical)
Values (" & Logicalnme & ")
Values:
Logicalnme - True
When I run this query in VBA in Excel, I get this error message
Syntax Error in Insert into Statement
Kindly confirm shall I use "Logical" as column name or this is the reserved keyword?
Thanks in advance.
There isn't a problem with your field name, you just need to enclose your INSERT column name in square brackets. You also need to choose a valid value in the VALUES clause:
INSERT INTO Data_CustomerTransmit_Tbl ( [Logical] )
VALUES (TRUE);
If you want to be prompted for the value to insert, you can use a parameter:
PARAMETERS [Please enter a Boolean value] YesNo;
INSERT INTO Data_CustomerTransmit_Tbl ( [Logical] )
VALUES ([Please enter a Boolean value]);
I presume you are trying to do this insert using VBA? If so, your syntax in building the SQL statement is correct, except you have some punctuation missing: double-quotes on each end.
"INSERT INTO Data_CustomerTransmit_Tbl (Logical) VALUES (" & Logicalnme & ")"
Further, as you have split the string over two lines (breaking before VALUES), you must also terminate the first line of the string with: ' " & _' (space,double-quote,space, ampersand, space, underscore) in order to indicate that the string continues to the next line. Then you begin the next line with double-quotes:
"INSERT INTO Data_CustomerTransmit_Tbl (Logical) " & _
"VALUES (" & Logicalnme & ")"
In VBA the code should look like this:
Docmd.RunSQL("INSERT INTO Data_CustomerTransmit_Tbl (Logical) VALUES (" & Logicalnme & ");"
The SQL query you alluded to - have you tried to execute it manually in the query editor using the same value(s) you are trying to pass from Excel? That would immediately provide more verbose feedback if there is an issue with the query or the data.
Regarding the Boolean field, make sure you are receiving a True/False that you are expecting, not a bit field, 0 and 1. I like to make quick log entries in a table or a file when troubleshooting to see the raw data.
Use Cbool function:
Insert Into Data_CustomerTransmit_Tbl (Logical)
Values (" & Cbool(Logicalnme) & ")
Add single quotes around values?
sql = "INSERT INTO Data_CustomerTransmit_Tbl (Logical) " & _
"VALUES ('" & Logicalnme & "')"
docmd.runsql sql

How to use a INSERT INTO SELECT query in Access VBA?

I have one table called Student, which contains information on a student such as their name.
Another table called Exam which has a date the exam was taken and the name of a student as the primary key.
I have a form that can be used to select multiple students from a list box that will then be inserted into the Exam table on the date selected.
I believe my syntax is correct because if I use Access's query builder and copy/paste my SQL query and get rid of the form stuff it will work as expected.
The error I get when I try to run it from VBA is that Exam.Exam_Date is unknown and to check my spelling. I spell it how it is spelled in the table.
Is it possible to use an INSERT INTO SELECT query within VBA in Access?
Here is my code:
Private Sub add_Click()
Dim Students As String
Dim i As Integer
Dim dbs As DAO.Database
Dim SQL As String
SQL = ""
Students = "'"
For i = 0 To Me.StudentListBox.ListCount - 1
'check to see if students name is selected
If Me.StudentListBox.Selected(i) = True Then
'list student names in a string separated by commas
Students = Students + CStr(Me.StudentListBox.ItemData(i)) & "','"
End If
Next
If IsNull(Me.ExamDate) Then 'check if user entered an Exam date
MsgBox "Please select a date for the Exam."
ElseIf Students = "'" Then 'check if user selected ant Students
MsgBox "Please select Students to add to an Exam."
Else
'remove trailing comma
Students = Left(Students, Len(Students) - 2)
'sql query to add list of Students to an Exam on specified date
SQL = "INSERT INTO Exam (Exam.Exam_Date, Exam.Student_Name) SELECT '" & CDate(Me.ExamDate) & "', Students.Full_Name FROM Students WHERE Students.Full_Name IN (" & Students & ");"
DoCmd.RunSQL SQL
End If
End Sub
I understand you may have already found your issue but I do want to point out some other items.
It is a very interesting setup building the WHERE IN clause. Alternatively, you could have iterated an INSERT INTO ... VALUES inside the For/Next loop:
INSERT INTO Exam (Exam_date, Student_Name)
VALUES(#" & Me.ExamDate & "#, '" & Me.StudentListBox.ItemData(i) & "')
Also check your Exam_Date field. From your query it looks like you retain date as a string field but if date/time field, VBA queries require # # instead of single quotes. Also no need for conversion functions, CStr or CDate, if already formatted to these date types by the form.
Finally, for database design recommendation, you should use StudentID inside the Exam table instead of relating both tables by Full_Name: better indexing, primary/foreign key referential integrity, data storage efficiency. Plus, if names have quotes no need for escaping or misspellings and integer values is safer in managing data between tables (i.e., duplicates, lookup).

Access query or VBA code to move data from one table to another depending on first row unique identifier

Is it possible to write a query to loop through the rows of a two column table, checking the first column for a certain identifier and copy the data in the second column into a new table?
Example:
tblSurveyData
FirstColumn Second Column
A0 John
A2 Smith
A3 05-01-1973
tblSurveyReport
FirstName MiddleName LastName DateOfBirth
John Smith 05-01-1973
Where A0 data would go to FirstName, A1 MiddleName, A2 LastName and A3 DateOfBirth. There are many more identifiers and fields but just as an example how would you do this with a query in Access or is VBA a better solution?
The only solution I came up with is the following VBA but this bypasses the two column table and tries to insert into the tblSurveyReport table. Unfortunately, it puts each piece of data into its own row which doesn't help.
If Identifier = "A0" Then
DoCmd.RunSQL "INSERT INTO tblSurveyReport " _
& "(FirstName) " _
& "VALUES ('" & Info & "')"
ElseIf Identifier = "A1" Then
DoCmd.RunSQL "INSERT INTO tblSurveyReport " _
& "(MiddleName) " _
& "VALUES ('" & Info & "')"
ElseIf Identifier = "A2" Then
DoCmd.RunSQL "INSERT INTO tblSurveyReport " _
& "(LastName) " _
& "VALUES ('" & Info & "')"
ElseIf Identifier = "A3" Then
DoCmd.RunSQL "INSERT INTO tblSurveyReport " _
& "(DateOfBirth) " _
& "VALUES ('" & Info & "')"
End If
However each piece of data is going into its own row and I need it all in the same row.
Any help is greatly appreciated.
Thanks in advance.
TC
Use INSERT INTO with a SELECT statement
INSERT INTO tblSurveyReport(FirstName) SELECT FirstName FROM tblSurveyData where FirstColumn = 'A0'
INSERT INTO tblSurveyReport(MiddleName) SELECT MiddleName FROM tblSurveyData where FirstColumn = 'A1'
You could run this using a DoCmd, as a query in Access, etc.
You will need something that would link your records together. What happens if the data gets re-sorted? How would you know that all the info in your example should be in the same record? I believe the only way to do something like this would be to create a 3rd field in your first table that determines which data belongs with which, something like a UserID. Then the table would look like this:
tblSurveyData
FirstColumn Second Column UserID
A0 John XX001
A2 Smith XX001
A3 05-01-1973 XX001
Then you could create a preliminary query like:
Select DISTINCT UserID from tblSurveyData
Use that as your "pointer" query and loop through the results, and then you can pull all the records with each UserID out and copy them into the new table. Or, you can inner join the "pointer" query and tblSurveyData, and then use a Crosstab query. The easiest way to do that would be to use the wizard to create it, and then just copy the code into your VBA.
EDIT: For easier readability for future readers, the SQL for the query you're asking for in your comment is:
SELECT Max(IIf([Identifier]="A0",[IValue],"")) AS FName, Max(IIf([Identifier]="A1",[IValue],"")) AS MName, Max(IIf([Identifier]="A2",[IValue],"")) AS LName, Max(IIf([Identifier]="A3",[IValue],"")) AS BDate FROM tblSurveyData;
You will need to change "First Column" in your sample data to "Identifier", and "Second Column" to "IValue" (or make the corresponding field name changes to the above SQL). I have tested this and it worked perfectly, giving you one record with all 4 values in corresponding fields. Once you've pasted that into a blank query, you can switch to Design View and change the query to an Append or MakeTable query and that will let you export the results to tblSurveyReport.
You could have simply two recordsets, like this:
1st recordset: rsSurveyData
2nd recordset: rsSurveyReport
The idea is to browse the first recordset along its records, and the second along its fields.
depending on the recordset object you are using (DAO or ADODB), the opening syntax will be slightly different, but you'll find all details in the help. I am using here the ADODB syntax for the 'Find', 'Move', and 'Update' methods. DAO recordsets need an extra 'Edit' method before changing the data. And I do not remember if the fields collection of the recordset object is indexed from 0 or 1 ...
Then:
rsSurveyData.moveFirst
rsSurveyReport.Find "FirstName ='" & rsSurveyData.fields("A0") & "'"
if rsSurveyReport.EOF then
'do what you have to do when the record does not exist, for example:'
rsSurveyReport.addNew
rsSurveyreport.fields(1) = rsData.fields(1)
Else
'you''ve just found the record that needs to be updated'
for i = 2 to rsSurveyData.recordcount
rsSurveyData.move i, 1
rsSurveyReport.fields(i)=rsSurveyData.fields(1)
next i
rsSurveyReport.update
Endif

VB.NET -> SQL Exporting String "901-0656" to not be 245 (901 minus 656)

I am trying to add new records to a Access database through VB.NET. The table "Quantities" has three columns:
PartNumber (string), PadsPerStrip (integer), and Verified (boolean)
The format that we use for PartNumber is ###-####-### (ie 901-0656-000). When I run my code everything is added correctly but math is performed on Part number so that the - is treated as a minus sign even though it is a string. Here is my sql command:
cmdInsert.CommandText = "INSERT INTO Quantities (PartNumber, PadsPerStrip, Verified) VALUES ( " & partNum & ", " & updatingPPS.ToString() & ", No);"
When viewing the command in a MsgBox it shows up as:
INSERT INTO Quantities (PartNumber, PadsPerStrip, Verified) VALUES (901-0656-000, 3, No);
Is there a way to make it skip the math operator when exporting the part number?
Make sure to enclose the part number with quotes. Without that, the value is not considered as a string when run in the database.

insert into related tables in same time

I'm working on vb.net project. I'm using VS2010 and SQL Server 2008.
I have many tables in my database, amongst them members and bank.
members contains columns: id_member, name, mobile, tel
bank contains id_bank, name_bank
Then I created member_bank table with 2 columns: members.id and bank_id for the m:n relationship between those two tables.
How can I insert details into members and join member id directly with bank id in the member_bank table ?
I wrote this code put it doesn't work:
Dim saveok As Boolean = wnclass14.SQLExicute("Insert Into members (member_name,member_id,mobile,tel) values ('" & TextstdntName.Text & "','" & Textid.Text & "','" & TextMobile.Text & "','" & Texttel.Text & "')")
If saveok = True Then
Dim saveok1 As Boolean = wnclass14.SQLExicute("Insert Into member_bank (id_member,id_bank) values (" & ComboBoxBank.SelectedValue & ") where member_bank.id_member=members.id")
If saveok1 = True Then .......
Part of the trick here is that you kind of want all of these to take place as part of a single transaction. Thankfully, it's not that hard to do this by sending multiple statements in a single call to your "SQLExicute" function (fix your spelling please):
wnclass14.SQLExicute( _
"BEGIN TRANSACTION;" & _
"DECLARE #NewID Int;" & _
"INSERT INTO members (member_name, mobile, tel) " & _
" VALUES ('..', '555-1234', '555-5678');" & _
"SELECT #NewID = Scope_Identity();" & _
"INSERT INTO member_bank (id_member, id_bank) " & _
" VALUES (#NewID, '1234');" & _
"COMMIT;)
And while we're here, you really need to fix this function so that it's also asking for parameter data.
It is not okay to to use string concatenation to include user-entered data in your sql statements.
It is not okay to skip this because you're still learning. And
it is not okay to "just get it working" first and then go back and fix the security issues afterwards
I assume you want to return the memberid from the members table after you do an insert? If so, you need to look into SCOPE_IDENTITY(). This should return the last Identity that was inserted into the table for your scope.
Here is a good article:
http://msdn.microsoft.com/en-us/library/ms190315.aspx
I'd supply code, but I don't really understand yours.
Good luck.