Running an SQL string in VBA? - ms-access

Iv created the SQL string sql in ms access vba but when it runs it prints the string in the debug window but doesn't actually run the string to add a record to the table like I want it to.
Public Sub EmpoyeesTable_Click()
Dim sql As String
sql = "INSERT INTO Employees " & _
"VALUES " & "(1, 'James', 'Dan', 'n6 indro Rd', 0943747, 30.24);"
Debug.Print sql
End Sub
Ultimately I want to use SQL strings to take input from a form when submit is clicked and add it to a table? Is this even the right approach?

There are many ways to run SQL strings in VBA. Each have their own advantages, and disadvantages. The most common ones are:
DoCmd.RunSQL sql
Runs the SQL just as it would if you executed a query. Popup will occur when you add, delete or modify records. You can use UDFs and form parameters
DoCmd.SetWarnings False
DoCmd.RunSQL sql
DoCmd.SetWarnings True
Disables warnings, then runs the SQL like in the previous way, then sets warnings back on.
CurrentDb.Execute sql
Executes the SQL over a DAO connection to the current database. You can't use UDFs and form parameters here. No warnings are shown. It just executes the SQL.
CurrentProject.Connection.Execute sql
Executes the SQL over an ADO connection to the current database. Very similar to the DAO connection, but there are subtle differences. For example, you can execute DDL statements that contain the Decimal data type, and set Check constraints in this way, while both are not allowed in any of the other ways.
You can read about using parameters with these different ways here. That's strongly recommended if you are going to insert values that aren't constant, to avoid bugs and SQL injection.

If you think simply then just change your Debug.Print sql to DoCmd.RunSQL (sql)
Private Sub Command0_Click()
Dim sql As String
sql = "INSERT INTO Employees " & _
"VALUES " & "(1, 'James', 'Dan', 'n6 indro Rd', 0943747, 30.24)"
DoCmd.RunSQL (sql)
End Sub
If you want take values from form then refer each value from form control like text box. See the below codes.
Private Sub Command0_Click()
Dim sql As String
sql = "INSERT INTO Employees VALUES (" & _
"'" & Me.Text1 & "'," & _
"'" & Me.Text2 & "'," & _
"'" & Me.Text3 & "'," & _
"'" & Me.Text4 & "'," & _
"'" & Me.Text5 & "'," & _
"'" & Me.Text6 & "');"
DoCmd.RunSQL (sql)
End Sub
If the field value is number type the you can remove singe quote (') from code for those field.

Related

SQL code in VB MS Access inserts the new records to the middle of the table, not at the botom

In MS Access, I need to insert new records using SQL code.
I wrote the following code in VB and it inserts the code to the middle of the table.
Is there any chance to find out the reason?
sql = "INSERT INTO Audit_riskModelHistory (Action, User, modelKey, modelEventKey) " & _
"VALUES ('New Record Inserted', 'Mike-Admin', " & _
Me.cmb1.Value & ", " & Me.cmb2.Value & ")"
DoCmd.SetWarnings False
DoCmd.RunSQL (sql)
DoCmd.SetWarnings True
I tried looking at the properties of the table but I did not find the reason.

currentdb execute does not insert

I'm having trouble with Access VBA. I made the following code to insert some data to my SQL DB.
Private Sub btnFilmKijkenKlant_Click()
CurrentDb.Execute "INSERT INTO watchhistory (movie_id, customer_mail_address, watch_date, price, invoiced) VALUES (" & movie_id.Value & ", '" & Me.txtEmail & "', Date(),'" & price.Value & "', '0')"
End Sub
When the user hits the button I want some data to be transferred to the DB.
I don't get any errors but it just doesn't insert...
I made txtEmail field for testing. I got an e-mail field in another form that I want to use as customer_mail_address.
When I include the dbFailOnError option with CurrentDb.Execute, Access complains "ODBC Call failed", but I don't understand why.
Dim db as Database
Set db = CurrentDb()
db.execute(......)

DoCmd.RunSQL mySql got Run-time error '3464'

I have this simple code of vba access to update product in the database. But when I debug, it stops at the DoCmd statement and got run-time error. I've made research about this kind of error and code, and had changed the code but still caused an error. Below is my simple code to update the product value.
Sub UpdateProduct()
Dim mySql As String
mySql = "UPDATE " & Forms!UPDATE_PRODUCT!cbxLensType _
& " SET LOT_NO = " & Forms!UPDATE_PRODUCT!txtLotNo _
& " WHERE EAN_CODE = " & Forms!UPDATE_PRODUCT!txtEan & ";"
DoCmd.RunSQL mySql
End Sub
Could you help me to explain what is the problem to my code? Is it because of the update syntax?
Thanks in advance.
**New to access vba
Since EAN_CODE is Text type you need to enclose it inside single quotes.
Sub UpdateProduct()
Dim mySql As String
mySql = "UPDATE [" & Forms!UPDATE_PRODUCT!cbxLensType _
& "] SET LOT_NO = " & Forms!UPDATE_PRODUCT!txtLotNo _
& " WHERE EAN_CODE = '" & Forms!UPDATE_PRODUCT!txtEan & "';"
DoCmd.RunSQL mySql
End Sub
If LOT_NO is also a Text type, make sure that it is also enclosed in Single quotes.

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

Preserving Single Quotes in Access

I have created a form in Access 2010 that is used to insert data into an existing table. The table contains a Keywords field, Source combo box, and a Code text box where i write the data to be inserted and there is a button for executing the query. The code for the form is:
Private Sub cmd_go_Click()
Dim insertstring As String
insertstring = "INSERT INTO KWTable (KW, Source, Code) VALUES('" & text_key.Value & "','" & combo_source.Value & "','" & txt_code.Value & "');"
DoCmd.RunSQL insertstring
End Sub
The code is simple, it inputs the data to the table so i can reference it for future use. Now the problem I am having is that when I try to add long bits of code that I use in SQL Server i get a syntax missing expression error which I am assuming is coming from the single quotes since the code is from SQL. I am getting the error because when i am trying to store a code i used in SQL Server it uses single quotes which access does not recognise. I think if I try to write in the code for the insert form something to help convert the single quotes into double quotes, then reconvert them back to single quoteswill help solve the problem. I just cant figure out how to do it and could really use some help.
Thank You
You can avoid trouble with included quotes in your inserted text by using a parameter query.
Consider an approach such as this for cmd_go_Click().
Dim strInsert As String
Dim db As DAO.database
Dim qdf As DAO.QueryDef
strInsert = "PARAMETERS pKW TEXT(255), pSource TEXT(255), pCode TEXT(255);" & vbCrLf & _
"INSERT INTO KWTable (KW, Source, Code) VALUES (pKW, pSource, pCode);"
'Debug.Print strInsert
Set db = CurrentDb
Set qdf = db.CreateQueryDef(vbNullString, strInsert)
qdf.Parameters("pKW") = Me.text_key.value
qdf.Parameters("pSource") = Me.combo_source.value
qdf.Parameters("pCode") = Me.txt_code.value
qdf.Execute dbFailOnError
Set qdf = Nothing
Set db = Nothing
However, I don't understand how JoinCells() fits in.
I use a function that handles Null Values, and escapes single quotes (by converting them to two single quotes) when creating SQL statements directly:
Function SafeSQL(ByVal pvarSQL As Variant) As String
SafeSQL2 = Replace(Nz(pvarSQL, ""), "'", "''")
End Function
Then in your routine you would have:
insertstring = "INSERT INTO KWTable (KW, Source, Code) VALUES('" & SafeSQL(text_key.Value) & "','" & SafeSQL(combo_source.Value) & "','" & SafeSQL(txt_code.Value) & "');"