VBA to Insert Values from Multi-Value Lisbox into Separate Table (Run-time error 3075) - vba

This is my first post and hoping to get some help. I have done plenty of research but can't determine where I'm going wrong. I simply want to loop through a multi-value listbox and add the values to a separate table.
I have code that I think should work but I keep getting Run-Time error 3075 Syntax error (missing operator) in query expression '1b'.
Here's my situation:
I have a table: qaTbl
I have two fields in this table. interactionID and defect (this is the multi-value listbox). Both fields are shortText.
For each record submitted, I want to place the interactionID and defect (regardless if one defect is selected or many) into a new table called callDefectsTbl.
The two fields in callDefectsTbl is interactionID and defect.
I have a form with a submit button (qaSubmit). The control for the listbox is 'defect'.
Here is the code tied to the Click() Event of the submit button:
Private Sub qaSubmit_Click()
Dim db As DAO.Database
Dim strSQL As String
Dim varItem As Variant
Set db = CurrentDb
' Add each defect selected in the list box to callDefectsTbl
With Me.defect
For Each varItem In .ItemsSelected
strSQL = _
"INSERT INTO callDefectsTbl " & _
"(interactionID, defect) VALUES (" & _
Me.interactionID & ", " & .ItemData(varItem) & ")"
db.Execute strSQL
Next varItem
End With
DoCmd.GoToRecord , , acNewRec
End Sub
I get a Run-time error 3075. It seems to be stopping when grabbing the value of defect. I have studied other code that is doing the same thing but I don't understand what I'm doing wrong.
Any help and thorough explanation would be greatly appreciated!!
Thanks!!

If shorttext change sql with single quote
strSQL = _
"INSERT INTO callDefectsTbl " & _
"(interactionID, defect) VALUES ('" & _
Me.interactionID & "', '" & .ItemData(varItem) & "')"

Related

INSERT INTO - errors, but allows input into table

For reasons I cannot see I get the following error message:
Compile error: Method or data member not found
when I use the following:
Private Sub cmd_Add_Click()
Dim strSQL As String
strSQL = " INSERT INTO BERTHAGE " _
& "(BOAT, LOCATION, BERTH_WEEK, BERTH_YEAR, BERTHED) VALUES " _
& Me.Add_Boat & "','" _
& Me.LOCATION & "','" _
& Me.txt_week & "','" _
& Me.txt_year & "','" _
& Me.In_Port & "');"
cmd_Clear_Click
End Sub
Once I click OK and use the refresh button the entry is put into the database, but each time I do an entry I have to go to the same process.
I would like to figure out what method or data is missing?
I should add that there is an outnumber primary key field on this table (Berth_ID), and each time I use the cmd_Add button a new ID number is created for the new record. This includes creating a new ID number for the new record that triggers the error.
Here is all the VBA associated with this form
Private Sub Form_Load()
DoCmd.RunCommand acCmdRecordsGoToLast
End Sub
Private Sub LOCATION_Change()
Me.txt_Cur_Flo = Me.LOCATION.Column(1)
Me.txt_Cur_Doc = Me.LOCATION.Column(2)
Me.txt_Cur_Ori = Me.LOCATION.Column(3)
End Sub
Private Sub cmd_Add_Click()
Dim strSQL As String
strSQL = " INSERT INTO BERTHAGE " _
& "(BOAT, LOCATION, BERTH_WEEK, BERTH_YEAR, BERTHED) VALUES " _
& Me.Add_Boat & "','" _
& Me.LOCATION & "','" _
& Me.txt_week & "','" _
& Me.txt_year & "','" _
& Me.In_Port & "');"
cmd_Clear_Click
End Sub
Private Sub cmd_Clear_Click()
Me.Add_Boat = ""
Me.LOCATION = ""
Me.txt_Cur_Flo = ""
Me.txt_Cur_Doc = ""
Me.txt_Cur_Ori = ""
Me.Add_Boat.SetFocus
End Sub
Private Sub cmd_Close_Click()
DoCmd.Close
End Sub
Consider the best practice of parameterization and not string concatenation of SQL mixed with VBA variables. Due to missing quotes, the compiler attempts to reference a column name and not its literal value. Instead, consider parameterization with defined types which is supported with Access SQL using QueryDefs. Notice below, SQL and VBA are complete separate.
SQL (save as stored query)
PARAMETERS prmBoat TEXT, prmLoc INT, prmBerthed INT;
INSERT INTO BERTHAGE (BOAT, LOCATION, BERTHED)
VALUES(prmBoat, prmLoc, prmBerthed)
VBA
Dim db As Database
Dim qdef As QueryDef
Dim strSQL As String
Set db = CurrentDb
Set qdef = db.QueryDefs("mySavedParamQuery")
' BIND PARAM VALUES
qdef!prmBoat = Me.Add_Boat
qdef!prmLoc = Me.LOCATION
qdef!prmBerthed = Me.In_Port
' EXECUTE ACTION QUERY
qdef.Execute
Set qdef = Nothing
Set db = Nothing
Even better, save your query with form controls intact and simply call OpenQuery:
SQL (save as stored query)
INSERT INTO BERTHAGE(BOAT, LOCATION, BERTHED)
VALUES(Forms!myForm!Add_Boat, Forms!myForm!LOCATION, Forms!myForm!In_Port)
VBA
Private Sub cmd_Add_Click()
Dim strSQL As String
DoCmd.SetWarnings False ' TURN OFF APPEND PROMPTS
DoCmd.OpenQuery "mySavedActionQuery"
DoCmd.SetWarnings True ' RESET WARNINGS
Call cmd_Clear_Click
End Sub
Missing opening parenthesis after VALUES. Also missing apostrophe in front of Me.Add_Boat. These special characters must always be in pairs, an even number by counting.
If Berth_Week and Berth_Year are number fields (and should be), don't use apostrophe delimiters.
If In_Port is a Yes/No field, don't use apostrophe delimiters.
The issue appears to be that I was doubling up the inputs into the 'week' and 'year' field. this was happening (I believe) because those text box fields were already accessing the week and year information directly from the default value on the BERTHAGE table. Essentially I went through each input and would run it individually waiting for the error to occur. Once it occurred I took it out of the INSERT INFO statement. With the removal of week and year, everything is working. That was a painful exercise, and still not complete, but I am back to a function form/DB so I'll take the small victories when they occur.
Private Sub cmd_Add_Click()
Dim strSQL As String
CurrentDb.Execute " INSERT INTO BERTHAGE " & "(BOAT, LOCATION, BERTHED) VALUES ('" & Me.Add_Boat & "'," _
& Me.New_Loc & "," _
& Me.In_Port & ");"
cmd_Clear_Click
DoCmd.Requery
End Sub`

Access VBA RunSQL Error

I'm trying to insert into a table the top x records from a query data-set. However I keep getting the run-time error '3061' Too few parameters. Expected 1. I've tried a few things but it doesn't make any difference.
Private Sub UpdateGA_Click()
Dim dbs As DAO.Database
Dim strSQL As String
Dim rounds As Integer
Dim playerid As Long
Set dbs = CurrentDb
rounds = Me.NoOfScores.Value
playerid = Me.lngPlayerID.Value
strSQL = "INSERT INTO [tbl_TopRounds] ( [lngPlayerID], [lngRoundID], [dblPlayedTo], [dteRoundDate]) " & _
" SELECT TOP " & Me.NoOfScores.Value & " [lngPlayerID], [lngRoundID], [dblPlayedTo], [dteRoundDate] FROM qry_LastRounds" & _
" WHERE [lngPlayerID] = " & Me.lngPlayerID.Value & _
" ORDER BY [dblPlayedTo], [dteRoundDate] DESC;"
dbs.Execute strSQL
End Sub
I'm expecting that x (based on a form parameter) records will be written to the tbl_TopRounds.
VB Error on executing
Any help would be appreciated.
Normally this error means that you made a mistake in field name. Set breakpoint on last command, run the sub, open immediate window and type ?strSQL. Copy received SQL text and try to run it in query builder, it will show column name which doesn't exist in the table. The error may be in the query qry_LastRounds, check it first by opening

VBA run time Error 3129 Illegal SQL-Statement

I'm trying to make a VBA Code to run a query when someone clicks on the button.
It always displays me the error in the title when I run it. Can someone help mes please? I'm thankful for every response.
Option Compare Database
Option Explicit
Sub btnNamebox_Click()
DoCmd.OpenForm "F-Smartphone-Hinzufuegen"
Dim strSQL As String
DoCmd.RunSQL (strSQL)
strSQL = "SELECT Nachname" & _
"FROM tblPersonal " & _
"WHERE Handynummer = " & Forms![F-Smartphone-Hinzufuegen]![FKHandynummer] & ";"
txtnamebox.Value = strSQL
End Sub
Your code makes little sense - you run a SQL statement before you define it, and you can't RunSQL a SELECT statement anyways.
Use DLookup() instead:
S = Nz(DLookup("Nachname", _
"tblPersonal", _
"Handynummer = " & Forms![F-Smartphone-Hinzufuegen]![FKHandynummer]), "")

VBA Append Query Using Access

I am attempting to add a button to a form to add the contents of the form as a new line in my table. I have written this line of code before, but this time it isn't working.
My form contains text and integers. 3 boxes on the form are auto-populated when the form loads. (Will the auto populated boxes change anything?)
Instead of trying to make the whole string work, I have reduced my code to just add one box (one of the auto-populated boxes). I get a Rune-time error '438': Object doesn't support this property or method.
I've tried googling the error, but I cannot find anything that applies.
The code is as follows:
Dim strInsert As String
strInsert = "INSERT INTO NLog(IDKEY) " & _
" Values(" & Me.TxtIdKey & ")"
Debug.Print strInsert
CurrentProject.Execute strInsert, dbFailOnError
MsgBox ("Entry Added")
When I look at the debug screen it shows the following:
INSERT INTO NLog(IDKEY) Values(OH08801405)
I am so frustrated! I am still very new to this, and I feel totally out of my element.
You could execute your INSERT statement with ADO like this ...
CurrentProject.Connection.Execute strInsert
Note CurrentProject.Connection.Execute, not CurrentProject.Execute, and don't include the DAO constant dbFailOnError when executing from ADO.
Or with DAO like this ...
CurrentDb.Execute strInsert, dbFailOnError
Also, you were attempting to insert a text value into the IDKEY field. Assuming text is the correct datatype for that field, add quotes around the value you're inserting ...
strInsert = "INSERT INTO NLog(IDKEY) " & _
" Values('" & Me.TxtIdKey & "')"
Then you should see Debug.Print output similar to this ...
INSERT INTO NLog(IDKEY) Values('OH08801405')
Without quotes surrounding OH08801405, the db engine will not understand it is supposed to be a string value it should insert, and instead will assume it is a parameter for which you haven't supplied a value.
I have to assume that the error message is happening at CurrentProject.Execute strInsert, dbFailOnError since your debug actually shows something.
You will need to set up a connection to your database and use db.Execute strInsert, dbFailOnError.
You declare a connection like this:
Dim db As DAO.Database
Set db = CurrentDb
So you should end up with something like:
Dim strInsert As String
Dim db As DAO.Database
strInsert = "INSERT INTO NLog(IDKEY) " & _
" Values(" & Me.TxtIdKey & ")"
Debug.Print strInsert
Set db = CurrentDb
db.Execute strInsert, dbFailOnError
MsgBox ("Entry Added")

Inserting into a different table from a form

I am trying to make an event when iputing data in a form on access, after the text box looses focus, if the box is not null I want the ID and the value to get stored into another table. After trying with the code below I get "Runtime error 3061 Too few parameters Expected 1". I have checked in debug mode and the values are getting carried over and brought to the string.
Private Sub Consolidate_LostFocus()
Dim queryString As String
queryString = "INSERT INTO [ReportMasterTable]([#], [Notes]) VALUES(" & [#].Value & ", " & [Consolidate].Value & ")"
If Consolidate.Text <> vbNullString Then
CurrentDb.Execute (queryString)
End If
End Sub
If either the # or the Notes fields in ReportMasterTable is text data type, you must add quotes around the values you attempt to INSERT.
For example, if both fields are text type:
queryString = "INSERT INTO [ReportMasterTable]([#], [Notes])" & vbCrLf & _
"VALUES ('" & [#].Value & "', '" & [Consolidate].Value & "')"
The situation will be more complicated if either [#].Value or [Consolidate].Value contains a single quote. You could double up the single quotes within the inserted values. However it might be easier to just switch to a parameterized query ... the quoting problem would go away.
Dim db As DAO.database
Dim qdf As DAO.QueryDef
Dim strInsert As String
strInsert = "PARAMETERS hash_sign Text (255), note_value Text (255);" & vbCrLf & _
"INSERT INTO [ReportMasterTable]([#], [Notes])" & vbCrLf & _
"VALUES (hash_sign, note_value)"
Set db = CurrentDb
Set qdf = db.CreateQueryDef("", strInsert)
qdf.Parameters("hash_sign").value = Me.[#]
qdf.Parameters("note_value").value = Me.[consolidate]
qdf.Execute dbFailOnError
Set qdf = Nothing
Set db = Nothing
You could also save the SQL statement as a named query and open and execute that instead of rebuilding the statement every time your procedure runs.
Is there any reason why you do not wish ti bind the form to the ReportMasterTable?
If you really have a control and field called #, you are facing a world of trouble.
If you have bound the form to ReportMasterTable and are also updating in a query, you are going to run into problems.
The lost focus event is a very bad event to choose, any time anyone tabs through the form, the code will run. After update would be better.
You are updating a text data type, but you have not used quotes.
"INSERT INTO [ReportMasterTable]([#], [Notes]) VALUES(" & [#].Value _
& ", '" & [Consolidate].Value & "')"