append query in VBA (run-time error 3067) - ms-access

I'm pulling seven values from unbound text boxes on a form into variables. Five of the variables are string type, two are double. I'm then using sql to append the data to a table using a where statement and a global variable which contains a foreign key I used from another table, since I was unsure how to use openargs with browseto...
Option Compare Database
Private Sub Form_Load()
Dim rowN, rowR, mat, crew, perCom As String
Dim budEst, curBud As Double
End Sub
Private Sub btnCapSubmit_Click()
rowN = Me.CAP_ROW_N
rowR = Me.CAP_ROW_R
mat = Me.CAP_MAT
crew = Me.CAP_CREW
perCom = Me.CAP_PER
budEst = Me.CAP_BUD_EST
curBud = Me.CAP_BUD_CUR
Dim appendIt As String
appendIt = "INSERT INTO CAPITAL " & _
"([CAPITAL].[CAP_ROW_N], CAPITAL.[CAP_ROW_R], [CAPITAL].[CAP_MAT], [CAPITAL].[CAP_CREW], [CAPITAL].[CAP_PER], [CAPITAL].[CAP_BUD_EST], [CAPITAL].[CAP_BUD_CUR]) " & _
"VALUES ('" & rowN & "','" & rowR & "','" & mat & "','" & crew & "','" & perCom & "','" & budEst & "','" & curBud & "') WHERE [PRO_ID] = '" & gblFind & "';"
Debug.Print appendIt
DoCmd.RunSQL appendIt
DoCmd.BrowseTo acBrowseToForm, "frmSearchEdit", "NavForm.NavigationSubform", , , acFormEdit
End Sub
Access complains with error #3067, "Query input must contain at least one table or query."
I have no idea what I'm doing.
I tried using debug.print but didn't see anything right off the bat. Then again I've been working on this database all day, so I could be overlooking something really easy.
P.S. I also tried replacing the variables with Me.CAP_ROW_N (textbox names), but no dice.

It's unclear what you are trying to do here, but an INSERT INTO ... VALUES () statement does not take a WHERE clause. Error 3067 is "Query input must contain at least one table or query." You are likely seeing this error because you have included a WHERE clause but you are not selecting existing values from a table.
Try this instead:
appendIt = "INSERT INTO CAPITAL " & _
"([CAPITAL].[CAP_ROW_N], CAPITAL.[CAP_ROW_R], [CAPITAL].[CAP_MAT], [CAPITAL].[CAP_CREW], [CAPITAL].[CAP_PER], [CAPITAL].[CAP_BUD_EST], [CAPITAL].[CAP_BUD_CUR]) " & _
"VALUES ('" & rowN & "','" & rowR & "','" & mat & "','" & crew & "','" & perCom & "','" & budEst & "','" & curBud & "');"
There are several other issues here as well. I will just list them and let you Google for more guidance:
You should use the .Execute DAO method instead of DoCmd.RunSQL because it allows for better error handling, especially when used with the dbFailOnError option.
You will eventually run into trouble using single-quotes on unescaped inputs. For example, WHERE LastName = 'O'Malley'
You appear to be treating all seven values as text by wrapping them in quotes, even though you said two of your values were numeric (double). Numeric values do not get quotes.

Do not qualify the field names with the table name in your field list.
A WHERE clause doesn't belong in an INSERT ... VALUES statement; get rid of that.
This is a smaller-scale example of the pattern I think you want:
appendIt = "INSERT INTO CAPITAL " & _
"([CAP_ROW_N], [CAP_ROW_R]) " & _
"VALUES ('" & rowN & "','" & rowR & "');"
However, I suggest you tackle this with a parameter query.
appendIt = "INSERT INTO CAPITAL " & _
"(CAP_ROW_N, CAP_ROW_R) " & _
"VALUES (pCAP_ROW_N, pCAP_ROW_R);"
Dim db As DAO.Database
Dim qdf As DAO.QueryDef
Set db = CurrentDb
Set qdf = db.CreateQueryDef(vbNullString, appendIt)
qdf.Parameters("pCAP_ROW_N") = Me.CAP_ROW_N.Value
qdf.Parameters("pCAP_ROW_R") = Me.CAP_ROW_R.Value
qdf.Execute dbFailOnError
Note I used the text box values for the parameter values directly --- instead of declaring variables to hold the text box values.
Also notice one of the benefits of parameter queries is you needn't bother with delimiters for the values: quotes for text; or # for dates.

Related

MS Access Table filtered by checkboxes from a form, creating a new table

I want to create a new table "TblMany", filtering values from other data table "TblControl".
Filtering with multiple checkboxes of a Form "FrmMany".
Table with data "TblControl":
Form with checkboxes, representing all values available in "Box?" columns from data table:
After pressing the button, it should create a new table (or recreate one existing) that shows rows with numbers selected in the "FrmMany"
Multiple selection needed:
I have done some tests with "iif" or "where" but i think it's only possible via VBA.
Any ideas?
You are correct that you will need to use VBA to do this. Firstly, you will need to loop the checkboxes to see if they are to be used in the selection of data. Once this has been done, you need to build a SQL string that inserts the data into the existing table. Something like this seems to work:
Private Sub cmdProcess_Click()
On Error GoTo E_Handle
Dim intLoop1 As Integer
Dim strSQL As String
For intLoop1 = 1 To 8
If Me("chk" & intLoop1) = True Then strSQL = strSQL & intLoop1 & ","
Next intLoop1
If Len(strSQL) > 0 Then
If Right(strSQL, 1) = "," Then strSQL = Left(strSQL, Len(strSQL) - 1)
CurrentDb.Execute "DELETE * FROM tblMany;"
CurrentDb.Execute "INSERT INTO tblMany " _
& " SELECT * FROM tblControl " _
& " WHERE Box1 IN(" & strSQL & ") " _
& " OR Box2 IN(" & strSQL & ") " _
& " OR Box3 IN(" & strSQL & ");"
End If
sExit:
On Error Resume Next
Exit Sub
E_Handle:
MsgBox Err.Description & vbCrLf & vbCrLf & "cmdProcess_Click", vbOKOnly + vbCritical, "Error: " & Err.Number
Resume sExit
End Sub
I am assuming that tblMany is an exact copy of of tblControl apart from field ID being an Autonumber in tblControl and just numeric in tblMany.
Rather than repeatedly deleting and inserting data (which will lead to bloat), you may find it better to use a query and modify its SQL as needed:
CurrentDb.QueryDefs("qryMany").SQL="SELECT * FROM tblControl " _
& " WHERE Box1 IN(" & strSQL & ") " _
& " OR Box2 IN(" & strSQL & ") " _
& " OR Box3 IN(" & strSQL & ");"

Current system datetime syntax in VB6.0 which is equivalent to sql datetime

brdSrNo = txt_Board_SrNo.Text
usrname = txt_User_Name.Text
ndate = Format$(Now, "yyyy-mm-dd hh:mm:ss")
voltMeas1 = txt_VoltMes.Text
rs.Open "insert into duct_test values(" & brdSrNo & ",'" & ndate & "'," & usrname & ", " & voltMeas1 & ")", con, adOpenDynamic, adLockBatchOptimistic
'here I get the error'
I tried the above code but the error appears as:Incorrect syntax near','. Is there anyway to get the datetime like this:2015-10-30 17:09:22.000, as we get in sql
thanks #nabuchodonossor & #Fred, I got the Datetime pblm fixed. Now I got another error.. where, if voltMeas1=12.5 r something that takes an voltage measure... the error shows : "Arithmetic overflow error converting numeric to datatype numeric" ,In the sql table VoltageMeasure data type is Numeric(2,2).. can u suggest anthying?
you can also use the server time:
instead of:
rs.Open "insert into duct_test values(" & brdSrNo & ",'" & ndate & "'," & usrname & ",
you can write:
rs.Open "insert into duct_test values(" & brdSrNo & ", GETDATE(), " & usrname & ",
and implement the changes of mentioned by Fred
I can see a couple of things wrong here
You are inserting a record so you do not need a recordset as you are not returning anything. Use cmd .Execute instead of rs.Open.
usrname is a string so needs to be wrapped in single quotes '
Your final code should like more like:
Private Sub cmd_update_Click()
Dim strSQL As String
Dim con As ADODB.Connection
Set con = New ADODB.Connection
con.ConnectionString = "Provider=SQLOLEDB;Data Source=SUVI.suvi.local;InitialCatalog=SUVI;Database=BLS;uid=sa;pwd=123458;"
con.Open
strSQL = "insert into duct_test values(" & brdSrNo & ", GetDate(),'" & usrname & "', " & voltMeas1 & ")"
con.Execute strSQL, , adCmdText
con.Close
Set con = Nothing
End Sub
As a side note it is advisable to replace single quotes in any data input by a user with double single quotes. For example:
usrname = Replace$(usrname, "'", "''")
This will help against SQL injection attacks. Im not saying it will total prevent this but it will help.
If the date you are inserting is always the current date and time you can, as
nabuchodonossor point out, use GetDate().

Getting a Key Violation Error when trying to use an Update String from a form

I have a form that allows people to add new employees but they need to be able to edit or update the existing employees as well.
So I added a button to allow them to make changes right on the form, click the update button and the record they were working on would be updated right away.
When I tested it however the string runs and even pops up a warning letting you know you are about to permanently change a record. But then it throws up an error stating "did not update record due to Key Violation"
I have included my "On Click" Event code
DoCmd.RunSQL "UPDATE EntList " & _
"SET EntList.BusinessUnit = '" & Me.cboBUnit & "', EntList.EntityName = '" & Me.txtEntName & "', EntList.Position = '" & Me.txtPos & "', EntList.Location = '" & Me.cboLoc & "', EntList.Client = '" & Me.cboClient & "', EntList.Dept = '" & Me.cboDept & "', EntList.DistKey = '" & Me.txtDistKey & "', EntList.Salary = '" & Me.txtSalary & "', Entlist.Currency = '" & Me.cboCurrency & "', EntList.[SG&A] = '" & Me.txtSG_A & "', EntList.BillRate = '" & Me.txtBillRate & "', EntList.[Util%] = '" & Me.txtUtil_ & "', EntList.MeritDate = '" & Me.txtMeritDate & "', EntList.[Merit%] = '" & Me.txtMerit_ & "' " & _
"WHERE EntList.EntityID = '" & Me.txtEntID.Value & "';"
I am wondering what I am missing that is causing this error.
If I followed the comments correctly, you have resolved the key violation error which occurred because one of the update values did not satisfy the requirement of a defined relationship which enforces referential integrity. In that situation, Access reports the relationship violation as key violation.
And, with that problem resolved, you're now facing a type mismatch between an update value and the destination field.
Your UPDATE included quotes around every value it supplied. Likely the current error is because a destination field is numeric data type instead of text.
So you can examine the data type of each destination field and make sure your UPDATE includes quotes around the values for text fields, # around the values for Date/Time fields, and no delimiters around the values for numeric fields.
While that is possible, it's also time-consuming and error-prone. A better approach is to use a parameter query so you needn't fiddle with delimiters.
Here is an abbreviated sample of the approach I'm suggesting. You will have to extend it to include the other fields I left out.
Dim strUpdate As String
Dim db As DAO.Database
Dim qdf As DAO.QueryDef
strUpdate = "UPDATE EntList AS e" & vbCrlf & _
"SET e.BusinessUnit = pBusinessUnit, " & _
"e.EntityName = pEntityName" & vbCrLf & _
"WHERE e.EntityID = pEntityID;"
Debug.Print strUpdate
Set db = CurrentDb
Set qdf = db.CreateQueryDef(vbNullString, strUpdate)
qdf.Parameters("pBusinessUnit") = Me.cboBUnit.Value
qdf.Parameters("pEntityName") = Me.txtEntName.Value
qdf.Parameters("pEntityID") = Me.txtEntID.Value
qdf.Execute dbFailOnError
Set qdf = Nothing
Set db = Nothing

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

Checkbox value in VBA yes/no

I have a form where I have a combobox and 4 checkboxes. I want to insert value from combobox and from chechboxes, when it is checked it is true and when not it is false.
When I put check on checkbox should insert value YES in database and when I don't put check it will be NO.
Private Sub Command12_Click()
Dim strSQL As String
Dim rst As New ADODB.Recordset
Dim myval As String
If Me.Check2 Or Me.Check6 Or Me.Check8 Or Me.Check10 = -1 Then
myval = "Yes"
Else
myval = "No"
strSQL = "INSERT INTO Declaratie (Код_предр, Декларация, Данные_фирмы,
Список_траспрота, Список_водителей) " & _
" VALUES ('" & Me.НаимПредпр & "','" & Me.Check2 & "','" & Me.Check6 & "','"
& Me.Check8 & "','" & Me.Check10 & "')"
Call AttServ(strSQL, rst) 'выполнение запроса
End If
End Sub
You can simply format a YesNo (boolean) control to get a Yes or a No, but this is probably not such a good idea. You would be better storing the YesNo as it is in a YesNo field and just formatting your form to show a Yes or No. Note that the code below will not work with a YesNo data type, because you are storing text.
Private Sub Command12_Click()
Dim strSQL As String
Dim rst As New ADODB.Recordset
strSQL = "INSERT INTO Declaratie (Код_предр, Декларация, Данные_фирмы,
Список_траспрота, Список_водителей) " & _
" VALUES ('" & Me.НаимПредпр & "','" _
& Format(Me.Check2, "Yes/No") & "','" _
& Format(Me.Check6, "Yes/No") & "','"
& Format(Me.Check8, "Yes/No") & "','" _
& Format(Me.Check10, "Yes/No") & "')"
Call AttServ(strSQL, rst) 'выполнение запроса
End Sub
If Me.Check2.VALUE = 1 Then
myval = "Yes"
Else
myval = "No"
END IF
Add this code to every check box, cause as i know that you cannot using a code to made all checkbox or radiobutton do same thing. You must using a checkbox or radiobutton own code even it's same