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
Related
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 & ");"
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.
I have a database that I am trying to send information contained on a form combined with selected items in a listbox to a table when the user clicks a Send button. I have the code setup that should copy my information but get a syntax error and I am not sure why... I have tried several different things and can't get it to work. I have included the code below:
Private Sub ctrSend_Click()
Dim intI As Integer
Dim lst As ListBox
Dim varItem As Variant
Set lst = Me![lstShipping]
With lst
If .ItemsSelected.count = 0 Then Exit Sub
For Each varItem In .ItemsSelected
CurrentDb.Execute "INSERT INTO ShipInv ([Order], [ShipDate], [BIN], [SKU], [Lot], [QtyProd])" _
"VALUES ('" & Me.[ctrSOrder] & "'," & Me.[ctrSDate] & ",'" & .Column(0, varItem) & "'," & .Column(1, varItem) & "," & .Column(2, varItem) & "," & .Column(3, varItem) & ");", dbFailOnError
Next
End With
End Sub
For a situation like this, I always reccommend using a string to hold the constructed SQL so that you can easily print the string to the immediate window to check how certain values have broken your SQL.
So, try adding
Dim strSQL As String
strSQL = "INSERT INTO ShipInv ([Order], [ShipDate], [BIN], [SKU], [Lot], [QtyProd])" _
"VALUES ('" & Me.[ctrSOrder] & "'," & Me.[ctrSDate] & ",'" & .Column(0, varItem) & "'," & .Column(1, varItem) & "," & .Column(2, varItem) & "," & .Column(3, varItem) & ");"
Debug.Print strSQL
CurrentDb.Execute strSQL 'remove dbFailOnError temporarily so that failure will stop code
My blind guess is that if ShipDate is a date field(not text), you'll need to format that value with Format(Me.[ctrSDate], "\#mm\/dd\/yyyy\#" before pasting it into the SQL.
I used a different approach and it works out great...
Private Sub ctrSend_Click()
Dim intI As Integer
Dim lst As ListBox
Dim varItem As Variant
Dim rst As DAO.Recordset
Set lst = Me![lstShipping]
Set rst = CurrentDb.OpenRecordset("ShipInv", dbOpenTable)
With lst
If .ItemsSelected.count = 0 Then Exit Sub
For Each varItem In .ItemsSelected
rst.AddNew
rst!Order = Me.[ctrSOrder]
rst!EntDate = Date
rst!ShipDate = Me.[ctrSDate]
rst!BIN = .Column(0, varItem)
rst!SKU = .Column(1, varItem)
rst!Lot = .Column(2, varItem)
rst!QtyProd = .Column(3, varItem)
rst.Update
Next
End With
rst.Close
Set rst = Nothing
MsgBox "Warehouse Inventory Updated", vbOKOnly, "Inventory Confirmation"
End Sub
I'm trying to update records in my form. It's a restaurant reservation system. Given the Table #, the form can let the user input the Customer ID of the person reserving, the reservation time and date. But when I click on the "update" button in my form, a text box will pop up with this:
And whatever I put in it, the runtime error "too few parameters. expected 1." pops up. Sometimes a "Reserved Error" will pop up. Could someone help me? It's the last step before I could finally finish this project.
This is my code for updating the record:
Private Sub Command8_Click()
On Error GoTo errHandling
Dim strSQL As String
strSQL = "UPDATE tblReserve SET CustomerID = " & """" & Me.txtCustID & """" & _
", ResDate = " & """" & Me.txtResDate & """" & ", ResTime = " & """" & Me.txtTime & """" & " WHERE TableNum =" & Me.TableNum
DoCmd.SetWarnings False
DoCmd.RunSQL strSQL
DoCmd.SetWarnings True
CurrentDb.Execute strSQL, dbFailOnError
DoCmd.Close
Exit Sub
errHandling:
MsgBox Err.Description
End Sub
Screenshot of VBA editor with Debug.Print strSQL
As revealed in our [chat][1], the essence of the problem was that [TableNum] is a text field and therefore its value had to be enclosed in quotes:
"... WHERE TableNum = '" & Me.TableNum & "'"
[1]: https://chat.stackoverflow.com/rooms/42746/discussion-between-nutellafella-and-gord-thompson)
Try something like this
strSQL = "UPDATE tblReserve SET CustomerID = " & Me.txtCustID & _
", ResDate = " & "'" & Me.txtResDate & "'" & ", ResTime = " & "'" & Me.txtTime & "'" & " WHERE TableNum =" & Me.TableNum
I am not sure why you have 2 sets of double quotes inside double quotes, I think what you were looking for is single quotes :)
However, there are much better ways to format sql than this. Also this seems like homework, so study up!
I have created a form with submit buttons on it.
I have entered the data in the text box and then clicked on submit button.But the data is not getting saved in the table.Also,it is not showing any error message. It is not working at all.
Private Sub CmdAddNew_Click()
'add data to table
CurrentDb.Execute "INSERT INTO tblemployee(firstname,lastname,Address,city)" & _
" VALUES('" & Me.txtfirstname & "','" & Me.txtlastname & "','" & Me.txtaddress & "','" & Me.txtcity & "')"
try this:
Private Sub CmdAddNew_Click()
Dim dbs As DAO.Database, Sqltext As String, iCount As Integer
Set dbs = CurrentDb
Sqltext = "INSERT INTO tblemployee(firstname,lastname,Address,city) " & _
"VALUES('" & Me.txtfirstname & "','" & Me.txtlastname & _
"','" & Me.txtaddress & "','" & Me.txtcity & "');"
Debug.Print "SQL statement generated with variables:" & vbCrLf & Sqltext
dbs.Execute Sqltext, dbFailOnError
iCount = dbs.RecordsAffected
Debug.Print "..." & iCount & " row(s) inserted"
End Sub
The debug.print messages will print to the immediate window (Ctrl+g) to view from VBA editor, you can delete them if you want to once you have confirmed it's working.