Inserting names from Excel to SQL Server table (VBA) - vba

I have written a simple code to loop through rows and insert values in column A (that is column containing full name) into an SQL Table. Something like this:
For i = 1 to LastRow
Command.CommandText = "INSERT INTO [TABLE] [Col1] VALUES ('" & Sheets("Sheet1").Cells(i, 1).Value & "')"
Next i
Issue arises when we have names like [O'Connell], which obviously creates a Bobby Table issue.
Are there any clever workarounds to avoid this?
Thanks
N.B. The full name is inserted from another SQL Table. In other words, perhaps a little difficult to edit.

You could use Replace to remove the problem character:
Command.CommandText = "INSERT INTO [TABLE] [Col1] VALUES ('" & _
Replace(Sheets("Sheet1").Cells(i, 1).Value,"'","") & "')"

Related

SQL msaccess insert single value into table

In my MSAccess database, I have this textbox "ProductName" where a user enters a value and presses a button to insert the value at the bottom of the table "Product". The column I want to add it to is "Product_ID" and my sql statement is
CurrentDb.Execute "INSERT INTO Tables!Product (Product_ID) VALUES ('" & Me.ProductName.Value & "')"
I found that this is breaking my code and I have been trying to fix it but cant seem to figure it out
I have also tried this
DoCmd.RunSQL "INSERT INTO Tables!Product (Product_ID) VALUES ('" & Me.ProductName.Value & "')"

How do I update a table with a form in access using VBA or a Macro?

I am doing my best to build my first database, but I have come up against a problem I just cannot find an answer to. I am a complete newbie in this forum and writing any sort of code so please be gentle.
I am trying to create a new record in a table when a student's name is double clicked inside a list box which is inside a form.
List box where I want to take first (StudentID) column value from = lstStudent
Combo box where I want to take the second (CourseID) column value from: cboCourseID
Text box where I want to take third (NoteID) column value from = txtCourseNoteID
The new record is being created in the desired table and there are no incorrect code errors but there are no values being carried across to the fields. The autonumber is being created (AttendanceID) but the other columns are blank. Here is my code:
Private Sub lstStudent_DblClick(Cancel As Integer)
CurrentDb.Execute "INSERT INTO tblAttendance (StudentID, CourseID, NoteID) VALUES ('me.lstStudent','me.cboCourseID','me.txtCourseNoteID')"
End Sub
The fields are populated, so this isn't the issue. The formatting is correct for the target fields and I can't think of anything else in my way.
The new record is being created in the desired table and there are no
incorrect code errors but there are no values being carried across to
the fields. The autonumber is being created (AttendanceID) but the
other columns are blank.
With this INSERT statement, you're supplying text values for those 3 fields in the new row ...
INSERT INTO tblAttendance (StudentID, CourseID, NoteID)
VALUES ('me.lstStudent','me.cboCourseID','me.txtCourseNoteID')
However StudentID, CourseID, and NoteID are numeric fields, so will not accept those text values. In that situation, there is nothing the db engine can insert. You still get a new row added (with the new autonumber value in AttendanceID), but those other fields are empty.
If you include the dbFailOnError option with .Execute, Access will notify you about the problem (error #3464, "Data type mismatch in criteria expression") and abort the insert --- a new row will not be added ...
CurrentDb.Execute "INSERT INTO tblAttendance (StudentID, CourseID, NoteID) VALUES ('me.lstStudent','me.cboCourseID','me.txtCourseNoteID')", dbFailOnError
Use an approach similar to what #HarveyFrench suggested, but eliminate the single quotes from the VALUES list ...
Dim strInsert As String
strInsert = "INSERT INTO tblAttendance (StudentID, CourseID, NoteID)" & vbCrLf & _
"VALUES (" & Me.lstStudent.Value & "," & Me.cboCourseID.Value & "," & _
Me.txtCourseNoteID.Value & ");"
Debug.Print strInsert ' <- view this in Immediate window; Ctl+g will take you there
CurrentDb.Execute strInsert, dbFailOnError
Based on what you've told us, I suspect that will work, but I'm not sure it's the best way to reach your goal. You could open a DAO.Recordset and add the new row there. Or if you can use a bound form, Access would automatically take care of storing a new row ... without the need to write code.
Change this
CurrentDb.Execute "INSERT INTO tblAttendance (StudentID, CourseID, NoteID) VALUES ('me.lstStudent','me.cboCourseID','me.txtCourseNoteID')"
to be this
CurrentDb.Execute "INSERT INTO tblAttendance (StudentID, CourseID, NoteID) _
VALUES ('" & me.lstStudent & "','" & me.cboCourseID & "','" & me.txtCourseNoteID "');"
See also here for useful info

Insert into an access table from SQL using recordset

I am using the following code to insert data in an access table from SQL using a recordset. This table is further used for other operations. While this is inserting the data into the table perfectly, the time taken by this huge. Should I use any other method to insert data into the table to reduce the time taken?
Do Until rs.EOF
DoCmd.RunSQL "INSERT INTO Table (Alpha,Beta,Gamma) VALUES(" & _
rs.Fields(0).Value & ",'" & rs.Fields(1).Value & "'," & rs.Fields(2).Value _
& " );"
rs.MoveNext
Loop
Create a linked table to the SQL table, say it's called MyLinkedTable
Create an Append query to append to your local Access table from your linked table. It will look something like this: INSERT INTO MyAccessTable (Field1,Field2...) SELECT Field1,Field2... FROM MyLinkedTable;
If you could select the data in the SQL UPDATE statement instead looping in VBA it would take a fraction of the time as all the work would be done by the server side.
You just need to do an INSERT INTO SELECT. We need more information on your RecordSet but you probably do not need it.
'Here we go, with just one line!
DoCmd.RunSQL "INSERT INTO Table (Alpha,Beta,Gamma) SELECT column1, column2, column2 FROM YourTable"
The SELECT statement is probably the same as the one you used for opening your Recordset.
Good luck!

Copy a column from one table into another table

I have tried this with ALTER TABLE to create the column followed by INSERT INTO. This kind of works, except each subsequent column starts after the previous column has ended. I guess this is how insert into works, so is there a workaround or another query I can build?
I have been trying with updates but its not working out.
For reference, these were the alter/insert queries i used.
SQL = "ALTER TABLE [results] ADD COLUMN [" & fld.Name & "_result] TEXT(25)"
db.Execute SQL
SQL = "INSERT INTO [results] ([" & fld.Name & "_result]) SELECT [Result] As
[" & fld.Name & "_result] FROM [newtable]"
db.Execute SQL
Your insert statement assumes that the results table has only one column that you need to insert data into. This is unlikely to be true, if the table already had other columns before you executed the ADD COLUMN.
You will need to keep track of the columns in the results table, and provide data (or a default value) for each column.
It is rather unusual to expand a table's structure from inside an application. What are you trying to accomplish? Are you sure you can't accomplish it better by defining fixed tables and then adding data from your application?
UPDATE
Okay, I think I understand what you're describing. On the first iteration, the ALTER TABLE creates the first column. The INSERT adds a bunch of rows that have data in this first column.
On the second interation, the ALTER TABLE creates a second column. The INSERT creates a whole bunch of new rows, but only the second column is populated. The first column is all NULL because you didn't provide values for it. And so on and so forth for the third and subsequent iterations.
If your actual intention is to duplicate the source table and its data, then you should create your results table in a single pass. You know the column structure, right? Use a CREATE TABLE statement. Then write a single INSERT statement somewhat like the following:
INSERT INTO [results]
([field1_result], [field2_result], [field3_result])
SELECT [Result] As
[field1_result, [field2_result], [field3_result]]
FROM [newtable]
Is this what you have in mind?
Before you enter into the loop create your [results] table as
SQL = "CREATE TABLE [results] SELECT [primary_key] FROM [newtable]"
db.Execute SQL
Then at every iteration of the loop execute
SQL = "ALTER TABLE [results] ADD COLUMN [" & fld.Name & "_result] TEXT(25)"
db.Execute SQL
SQL = "UPDATE [results] SET r.[" & fld.Name & "_result] = n.[Result] " &
"FROM [results] r, [newtable] n " &
"WHERE r.[primary_key] = n.[primary_key]"
db.Execute SQL
So, if you had your [newtable] at its first two iterations like
[primary_key] [Results] [primary_key] [Results]
1 A 1 D
2 B 2 E
3 C 3 F
Your [results] table (after the above two iterations) would look like
[primary_key] [fld1_result] [fld2_result]
1 A D
2 B E
3 C F

Inserting multiple rows to table - Access

I have an Access application in which I need to do a 'mass-update'.
I have a form on which I have a dropdown, a listbox, and a checkbox. I also have a Update button, and when the user clicks it, I want to insert rows into my table with the same value for the dropdown and checkbox fields in all the rows, but I want different values for each row depending on the list items that were selected.
I know that multiple rows can be inserted into a table using the UNION SELECT statement, but how am I supposed to apply that with a listbox?
Can anyone please help?
Thanks in Advance
You can create an update statement for each item selected. For example:
strSQLBase="INSERT INTO Table (Field1, Field2, Field3) Values (" & Me.Dropdown _
& "," & Me.CheckBox & ","
For Each itm In Me.ComboBox.ItemsSelected
strSQL = strSQLBase & Me.ComboBox.Column(0, itm) & ")"
CurrentDb.Execute strSQL
Next