Creating data entry form using button VBA - sql

I am trying to create a basic data entry form, however, it is turning into more trouble than I anticipated.. I have the form created, now I am just trying to INSERT the data into the DB (TEST). I am receiving an "Object Required" error. Any suggestions? All of the txt boxes are verified to be correct. This is all being done through Access VBA
Private Sub Command28_Click()
Dim sSQL As String
Set sSQL = "INSERT INTO TEST (Carrier_Ent_ID, Row_Insert_TS, Row_Update_TS,
Row_Insert_User_ID, Row_Update_User_ID, Carrier_Ent_Name, Active)
VALUES (" & Me.txtENTID & "," & Me.txtDate & "," & Me.txtDate & "," &
Me.cmboUserID & "," & Me.cmboUserID & "," & Me.txtENTNAME & ","
& Me.Txtactive & "); "
DoCmd.RunSQL.sSQL
End Sub

From what I can see there's a couple of mistakes in the code.
You only use SET when setting a reference to an object - sSQL is a text string.
DoCmd.RunSQL shouldn't have a full-stop after RunSQL- just the text string.
If Me.txtENTNAME is a text string it should have an apostrophe before and after it.
Private Sub Command28_Click()
Dim sSQL As String
'No Set & ' before and after Me.txtENTNAME (assuming it's text).
sSQL = "INSERT INTO TEST (Carrier_Ent_ID, Row_Insert_TS, Row_Update_TS, " & _
"Row_Insert_User_ID, Row_Update_User_ID, Carrier_Ent_Name, Active) " & _
"VALUES (" & Me.txtENTID & "," & Me.txtDate & "," & Me.txtDate & "," & _
Me.cmboUserID & "," & Me.cmboUserID & ",'" & Me.txtENTNAME & "'," & Me.txtActive & "); "
'No full stop after RunSQL.
DoCmd.RunSQL sSQL
End Sub

Related

Comparing multiple combo box (text) values in an Access VBA form to prevent duplicate entries with OR condition

Putting together a query (with SQL statement) button that checks for duplicate combobox entries (within one submission) before they happen.
Trying to comprehend why this works:
ElseIf Me.pc_cbox1 = Me.pc_cbox2 Then
MsgBox "Duplicate Program Code Error"
But this does not:
ElseIf (Me.pc_cbox1 Or Me.pc_cbox2 Or Me.pc_cbox3 Or Me.pc_cbox4 Or Me.pc_cbox5 Or Me.pc_cbox6 Or Me.pc_cbox7 Or Me.pc_cbox8) =
(Me.pc_cbox1 Or Me.pc_cbox2 Or Me.pc_cbox3 Or Me.pc_cbox4 Or Me.pc_cbox5 Or Me.pc_cbox6 Or Me.pc_cbox7 Or Me.pc_cbox8) Then
MsgBox "Duplicate Program Code Error"
Edit #1: Thought I was onto something with this loop:( ...
For intComboBox = 1 To 8
If Controls("pc_cbox" & intComboBox).ListIndex <> intComboBox Then
If Controls("pc_cbox" & intComboBox).Value = Controls("pc_cbox" & intComboBox).Value Then
MsgBox "Duplicate Program Code Error"
End If
End If
Next intComboBox
Edit #2: #HansUp's suggestion works! I am going to dissect this loop for the next hour to better understand the dictionary concept. I am new to VBA (3rd week) and I know this code is mostly spaghetti at this point but I have been forced into learning as I go at work. Here is what I have put together as an add funding (percentages) per program without duplicates. 'Program Code' is part of the primary key for the SQL table and therefore will not accept duplicate entries. I wanted to prevent being able to submit duplicates on the form to nip this issue in the bud.
Private Sub fundAdd_Click()
Dim strSQL As String, queryName As String, qdf1 As QueryDef, dct As Object, i As Long, strValue As String
queryName = "temp6"
If QueryExists(queryName) Then
DoCmd.DeleteObject acQuery, "temp6"
End If
Set dct = CreateObject("Scripting.Dictionary")
For i = 1 To 8
strValue = Nz(Me.Controls("pc_cbox" & i).Value, "NULL")
If dct.Exists(strValue) Then
MsgBox "Duplicate Program Code Error"
Exit For
Else
dct.Add strValue, vbNullString
End If
Next
If Me.percentTotal <> 1 Then
MsgBox "Total not equal to 100%"
Else
strSQL = "INSERT INTO position_funding2(box_id, program_code, percent) VALUES ('" & fundboxid_cbox & "','" & pc_cbox1 & "','" & percent1 & "'), " & _
" ('" & fundboxid_cbox & "','" & pc_cbox2 & "','" & percent2 & "'), ('" & fundboxid_cbox & "','" & pc_cbox3 & "','" & percent3 & "'), " & _
" ('" & fundboxid_cbox & "','" & pc_cbox4 & "','" & percent4 & "'), ('" & fundboxid_cbox & "','" & pc_cbox5 & "','" & percent5 & "'), " & _
" ('" & fundboxid_cbox & "','" & pc_cbox6 & "','" & percent6 & "'), ('" & fundboxid_cbox & "','" & pc_cbox7 & "','" & percent7 & "'), " & _
" ('" & fundboxid_cbox & "','" & pc_cbox8 & "','" & percent8 & "');"
MsgBox (strSQL)
Set qdf1 = CurrentDb.CreateQueryDef("temp6")
qdf1.Connect = "ODBC;Driver=MySQL ODBC 8.0 Unicode Driver;SERVER=sv03rm;UID=*****;PWD=*****;DATABASE=pobe;PORT=3306;DFLT_BIGINT_BIND_STR=1"
qdf1.SQL = strSQL
qdf1.ReturnsRecords = False
DoCmd.OpenQuery "temp6"
Me.List271.Requery
End If
Defaults
End Sub
Use your combo box values as keys of a Dictionary. Before adding each of those combo values, use the Exists method to check whether that value was already stored in the Dictionary. If it does exist, the one you're about to add is a duplicate, so display your MsgBox notice.
You didn't provide any context about where and how you intend to do the comparison. So, for my version, I used a command button's click event.
Private Sub cmdCompare_Click()
Dim dct As Object
Dim i As Long
Dim strValue As String
Set dct = CreateObject("Scripting.Dictionary")
For i = 1 To 8
strValue = Nz(Me.Controls("pc_cbox" & i).Value, "NULL")
If dct.Exists(strValue) Then
MsgBox "Duplicate Program Code Error"
Exit For
Else
dct.Add strValue, vbNullString
End If
Next
End Sub

Insert textbox value from a form into a table

I have a textbox(in form) and a field(in table) both named SerialNumber
This is the control source of the textbox: =([OrderNr] & (""+[Aantal]) & "" & [SapArtNr])
I can't seem to make the textbox save the value inside into the table.
Edit:
Option Compare Database
Private Sub Command82_Click()
' Add data to Table
CurrentDb.Execute "INSERT INTO Geleidelijst(SerialNmbr, InvoerOrderNr, InvoerAantal, InvoerVermogen, InvoerHSLSSpn) " & _
" VALUES(" & Me.SerialNumberLong & ",'" & Me.OrderNr & "','" & _
Me.Aantal & "','" & Me.Vermogen & "','" & Me.HSLSSpn & "')"
End Sub
But then I get error: 3075 Synax error missing operating in query expression. And if I add date as a format it doesn't work either.
Only when it's numbers, but when there's letters and dots and "/" for example, it won't work.
Any help would be nice, thanks.
Most likely, Aantal is numeric, so try without quotes:
CurrentDb.Execute "INSERT INTO Geleidelijst " & _
"(SerialNmbr, InvoerOrderNr, InvoerAantal, InvoerVermogen, InvoerHSLSSpn) " & _
"VALUES('" & Me.SerialNumberLong & "','" & Me.OrderNr & "'," & Me.Aantal & ",'" & Me.Vermogen & "','" & Me.HSLSSpn & "')"

When I write code inside textbox doesn't accept it

I have a textbox in a form. I use this textbox to write "Codes" and then I save it in the table in the database through the SQL insert statement, but the code doesn't accept to run and gives me an error message:
Run-Time error '3075'.
type of database: Access database
type of field data: LongText
What the problem and how to pass all same problems when I need to save codes inside the database field.
When I try to save the code without (') it's working!
I use this SQL Statement:
CurrentDb.Execute "Update Tbl_Codes Set [LP_ID]= " & Me.txtID & ",
[Code_Title]='" & Me.txtTitle & "'" _
& " ,[Code_Des]= '" & Me.txtDes & "',[Code_Key]= '" & Me.txtKey & "',
[Notes]= '" & Me.txtNotes & "'" _
& " Where [ID]= " & Me.txtID1 & ""
And I want to save this Code:
DSum("Field1";"Table";"Field2= '" & Value & "'")
Please change your code as follows. You need to escape single quotes by doubling them up. A simple replace will work for your.
CurrentDb.Execute "Update Tbl_Codes Set [LP_ID]= " & Replace(Me.txtID,"'","''") & ",
[Code_Title]='" & Replace(Me.txtTitle,"'","''") & "'" _
& " ,[Code_Des]= '" & Replace(Me.txtDes,"'","''") & "',[Code_Key]= '" & Replace(Me.txtKey,"'","''") & "',
[Notes]= '" & Replace(Me.txtNotes,"'","''") & "'" _
& " Where [ID]= " & Me.txtID1 & ""
DSum("Field1";"Table";"Field2= '" & Replace(Value,"'","''") & "'")

How can I insert data from an Access form into a sql table using VBA?

Here is what I have, I'm trying to take fields from an Access form (data comes from one linked sql table) and insert them into another linked sql table:
StrSQL = "INSERT INTO [dbo_Expense_Projection] ([StatusID],[TravellerUFID],[Email]) " & _
VALUES(" & Me.StatusID & ", " Me.TravellerUFID & ", " Me.SubmitterUFID & ", " Me.email & ")
DoCmd.RunSQL StrSQL
But I am getting this error
Compile error: Sub or Function not defined
I think you are just missing some double quotes:
StrSQL = "INSERT INTO [dbo_Expense_Projection] ([StatusID],[TravellerUFID],[Email]) " & _
"VALUES(" & Me.StatusID & ", " Me.TravellerUFID & ", " Me.SubmitterUFID & ", """ & Me.email & """)"
DoCmd.RunSQL StrSQL
You can try to print the contents of StrSQL and check the query before running it:
Debug.Print StrSQL
but I prefer not to create SQL strings with concatenated values (what happens if Me.StravellerUFID contains a double quote?)
I would suggest you to insert data using DAO:
Dim rs as Recordset
Set rs = CurrentDb.OpenRecordset("dbo_Expense_Projection")
rs.AddNew
rs!StatusID = Me.StatusID
rs!TravellerUFID = Me.TravellerUFID
' ...other fields
rs.Update
rs.Close
There are also some ampersands missing in the SQL-String:
StrSQL = "INSERT INTO [dbo_Expense_Projection] ([StatusID],[TravellerUFID],[Email]) " & _
"VALUES(" & Me!StatusID & ", " & Me!TravellerUFID & ", " & Me!SubmitterUFID & ", """ & Me!email & """)"
And I think you should use exclamation mark between "Me" and fieldname. But I do not want to argue with the experts here about that... ;)
Here is what ended up working:
Dim StrSQL As String
StrSQL = "INSERT INTO dbo_Expense_Projection (StatusID,TravellerUFID,Email)
VALUES('" & Form!StatusID & "','" & Form!TravellerUFID & "','" & Form!Email & "')"
DoCmd.SetWarnings False
DoCmd.RunSQL StrSQL
DoCmd.SetWarnings True

Missing comma error error inserting sql through access 2010 vba

Having the weirdest problem ever. I do have an sql insert statement, that properly works in sql. When i put that sql into vba it works very good from my pc. However, it does not work and shows sql error: missing comma. Where can be the problem??? I use Access 2010 plus, others use same Access version and having same ODB connections (DSN servers) . Some code example:
sql = "Driver={Microsoft ODBC for Oracle}; " & _
"CONNECTSTRING=(DESCRIPTION=" & _
"(ADDRESS=(PROTOCOL=TCP)" & _
"(HOST= ODB)(PORT=1520))" & _
"(CONNECT_DATA=(SERVICE_NAME=ABTL))); uid=IN; pwd=XXX;"
Set con = New ADODB.Connection
Set rec = New ADODB.Recordset
Set cmd = New ADODB.Command
con.Open sql
Set db = CurrentDb()
Set rst = db.OpenRecordset(strSQL)
Do While Not rst.EOF
insetSQL = con.Execute(" INSERT INTO STOCK (PNM_AUTO_KEY, PN, DESCRIPTION, HISTORICAL_FLAG, qty_oh, qty_adj, qty_available, CTRL_NUMBER, CTRL_ID, receiver_number, rec_date, serial_number,pcc_auto_key, cnc_auto_key, loc_auto_key, whs_auto_key, unit_cost, adj_cost, stc_auto_key, visible_mkt, remarks, ifc_auto_key, exp_date, unit_price, tagged_by, tag_date, owner, PART_CERT_NUMBER,ORIGINAL_PO_NUMBER, SHELF_LIFE, CTS_AUTO_KEY, MFG_LOT_NUM, AIRWAY_BILL )" & _
" VALUES ( " & rst![minimumas] & ", '" & rst![pn] & "', '" & "FROM_SCRIPT" & "', '" & "F" & "'," & rst![qty_oh] & "," & rst![qty_oh] & "," & rst![qty_oh] & "," & "G_STM_CTRL_NUMBER.nextval" & "," & "1" & ", '" & rst![receiver_number] & "', " & " TO_DATE('" & rst![rec_date] & "','YYYY-MM-DD'), '" & rst![serial_number] & "'," & rst![pcc_auto_key] & "," & rst![cnc_auto_key] & "," & rst![loc_auto_key] & "," & rst![whs_auto_key] & "," & rst![unit_cost] & "," & rst![unit_cost] & "," & "1" & ",'" & "T" & "', '" & rst![remarks] & "'," & _
"1" & ", " & " TO_DATE('" & rst![exp_date] & "','YYYY-MM-DD'), " & "0" & ",'" & rst![TAGGED_BY] & "', " & " TO_DATE('" & rst![tag_date] & "','YYYY-MM-DD'), '" & "" & "', '" & rst![PART_CERT_NUMBER] & "', '" & rst![ORIGINAL_PO_NUMBER] & "', '" & rst![SHELF_LIFE] & "', " & rst![CERT_SOURCE] & ", '" & rst![MFG_LOT_NUM] & "', '" & rst![AIRWAY_BILL] & "'" & " )")
Loop
It might be that one of the rescordset fields that is a string data type, has a value that contains a comma but you have not treated it as string.
eg
VALUES ( " & rst![minimumas] & ",
For the above code to work minimumas CANNOT contain any commas.
Are you certain that all the string fields int he recordset have been appended to the SQL string with a ' around them.
We need to see the sql string is created which then causes the error. Please provide this as requested.
=========================================================
PART 2 Viewing the SQL causing the error
replace
insetSQL = con.Execute(
with
on error resume next
strMySQl = the string currently used in the execute statement
insetSQL = con.Execute(strMySQl)
if err.number <> 0 then
stop
debug.print err.number, err.description
debug.print strMySQl
end if
then post the sql string that is printed in the immediate window to this site.
I would also suggest that you compare the SQL string generated on your machine with the other machines - just in case something weird is happening.