Microsoft Access passing variables to VB from Form - sql

I built a form with 2 combo boxes, one for Event and one for People. The two queries for the boxes include the Event_id and People_id but are not shown. The idea is to select the event from a drop down then add a person to attend the event. My problem is passing these two ID to the SQL update script.
Below is the VB; I receive a 424 error and calls the SQL as the area.
What's wrong?
Private Sub Command15_Click()
Dim dbs As DAO.Database, sql As String, rCount As Integer
Set dbs = CurrentDb
sql = "INSERT INTO Whos_Going (Event_ID, Who_is_invited) " _
& "VALUES(" & Event_id.Text & ", " & People_id.Text & ")"
dbs.Execute sql, dbFailOnError
rCount = dbs.RecordsAffected
If rCount > 0 Then
MsgBox "Person Added to Event"
'update listbox
conInfo.Requery
End If
End Sub

With VBA you need to construct the valid sql statement. All string literals must be enclosed into ', all dates must be enclosed into #. In addition to that, if your string variable contains an apostrophe it needs to be replaced with ''. The correct syntax will be:
sql = "INSERT INTO Whos_Going (Event_ID, Who_is_invited) " _
& "VALUES('" & Replace(Event_id.Text, "'", "''") & "', '" _
& Replace(People_id.Text, "'", "''") & "')"

Related

Access Run-Time error 2465. Can't find the field '1' referred to in your expression

I need help with this code.
Option Compare Database
Option Explicit
Private Sub BTNSEARCHOnetoOne_Click()
Dim SQL As String
SQL = "SELECT [00_SheetList-Revit-UNION].PACKAGE, [00_SheetList-Revit-UNION].DRAWING, [00_SheetList-Revit-UNION].DISCIPLINE, Hillsboro_OR_xlsx.FileName_Hillsboro_OR, Hillsboro_OR_xlsx.FilePath_Hillsboro_OR FROM Hillsboro_OR_xlsx, WHERE(([00_SheetList-Revit-UNION].PACKAGE) Like '" & Me.TXTKeywordsPackage & "') AND ((Hillsboro_OR_xlsx.FileName_Hillsboro_OR) Like ('*" & ([00_SheetList-Revit-UNION].DRAWING) & "*')"
Me.SubONEtoONEInsideJoin.Form.RecordSource = SQL
Me.SubONEtoONEInsideJoin.Form.Requery
Me.SubONEtoONENullJoin.Form.Requery
End Sub
Private Sub Detail_Click()
End Sub
I narrowed it down to this part of the code.
"...((Hillsboro_OR_xlsx.FileName_Hillsboro_OR) Like ('*" & ([00_SheetList-Revit-UNION].DRAWING) & "*')"
As I can take this part out and it works. Is this just syntax?
Currently, your SQL has a number of syntax issues:
Comma before WHERE clause;
Unclosed parentheses in last WHERE condition;
Unknown alias ([00_SheetList-Revit-UNION]) not referenced in FROM or JOIN clauses. Possibly you meant to cross join this source with Hillsboro_OR_xlsx.
See issues with current code with line breaks for illustration:
SQL = "SELECT [00_SheetList-Revit-UNION].PACKAGE," _
& " [00_SheetList-Revit-UNION].DRAWING," _
& " [00_SheetList-Revit-UNION].DISCIPLINE," _
& " Hillsboro_OR_xlsx.FileName_Hillsboro_OR, " _
& " Hillsboro_OR_xlsx.FilePath_Hillsboro_OR " _
& " FROM Hillsboro_OR_xlsx, " _
& " WHERE(([00_SheetList-Revit-UNION].PACKAGE) " _
& " Like '" & Me.TXTKeywordsPackage & "') " _
& " AND " _
& " ((Hillsboro_OR_xlsx.FileName_Hillsboro_OR) " _
& " Like ('*" & ([00_SheetList-Revit-UNION].DRAWING) & "*')"
These issues can be mitigated with parameterized queries (an industry best practice when writing SQL in application code) which is supported in MS Access using QueryDef Parameters. Below are a few advantages and further below adjustment to your setup.
Saving a stored query instead of a VBA string query allows it is to be optimized by engine and the Access GUI will not allow query to be saved with syntax issues;
Abstract data from code, specifically VBA variables from SQL statement;
Readability and maintainability is enhanced.
SQL (with no VBA)
Save below as a stored Access query, using parameters and table aliases. Also, [00_SheetList-Revit-UNION] is cross joined (comma-separated in FROM clause) as assumed above.
PARAMETERS [PackageParam] Text;
SELECT o.PACKAGE, o.DRAWING, o.DISCIPLINE,
h.FileName_Hillsboro_OR, h.FilePath_Hillsboro_OR
FROM Hillsboro_OR_xlsx h, [00_SheetList-Revit-UNION] o
WHERE ((o.PACKAGE) Like [PackageParam])
AND ((h.FileName_Hillsboro_OR) Like '*' & o.DRAWING & '*');
VBA
Private Sub BTNSEARCHOnetoOne_Click()
Dim qDef As QueryDef
Dim rst As Recordset
' OPEN SAVED QUERY
Set qDef = CurrentDb.QueryDefs("mySavedQuery")
' BIND PARAMETERS
qDef![PackageParam] = "*" & Me.TXTKeywordsPackage & "*"
' BUILD RECORDSET FROM QUERYDEF AND SET TO SUBFORM
Set rst = qDef.OpenRecordset()
Me.SubONEtoONEInsideJoin.Form.Recordset = rst
Me.SubONEtoONENullJoin.Form.Requery
Set qDef = Nothing
End Sub
It looks like that you had something wrong here
you have written
Like '" & Me.TXTKeywordsPackage & "'
but it has to be like this
Like '*" & Me.TXTKeywordsPackage & "*'
you had this part wrong
check this below part
Like ('*" & ([00_SheetList-Revit-UNION].DRAWING) & "*')
Make sure that you are getting the value from textbox. It looks like you are calling table column.
Carefully count your parenthesis.
There should be an additional ) at the very end.

ms access vba code for update records through form

I am new to MS Access 2007 & I know almost nothing about vba. ... I hv a table name F with fields F1, F2, F3, F4, F5 where 1st three are number fields & last two are text fields. In a form with textboxes: txtF1, txtF2, txtF3, txtF4, txtF5 and command button cmdUpdate, I want to update F5 in table F where F1=txtF1, F2=txtF2, F3=txtF3 and F4=txtF4 conditions staisfy. .. Kindly help with complete code.
In the cmdUpdate button's on click event, you need to place a procedure that will generate a sql command, then execute it.
Private Sub cmdUpdate_Click()
'Create a string variable to hold your sql command string
Dim strSQL As String
'Fill the variable with your sql command, plucking values out of your
'form as shown using the Me. operator. When using text values in your
'string, wrap them with the Chr(34)'s, which will insert quotation marks in
'your sql string when it's resolved.
strSQL = "UPDATE F SET F.F5 = " & Chr(34) & yourtextvaluehere & Chr(34) & _
" WHERE F1=" & Me.txtF1 & _
" AND F2=" & Me.txtF2 & _
" AND F3=" & Me.txtF3 & _
" AND F4=" & Chr(34) & Me.txtF4 & Chr(34)
'Execute the sql statement you've built against the database
CurrentDb.Execute strSQL, dbSeeChanges + dbFailOnError
End Sub

Using Cell reference in SQL query

I am using below VBA command to extract data using a SQL query by using a cell reference as filter.
Public Sub Run()
Dim SQL As String
Dim Connected As Boolean
Dim server_name As String
Dim database_name As String
Dim Allocation As String
Sheets("Perc").Select
Range("A6").Select
Selection.CurrentRegion.Select
Selection.ClearContents
' Our query
SQL = "SELECT Segmentation_ID,MPG,SUM(Segmentation_Percent) AS PERC " & _
"FROM dbo.HFM_ALLOCATION_RATIO " & _
"WHERE Segmentation_ID = " & Sheets("Perc").Range("A1").Value & " " & _
"GROUP BY Segmentation_ID,MPG ORDER BY MPG"
' Connect to the database
server_name = Sheets("General").Range("D1").Value
database_name = Sheets("General").Range("G1").Value
Connected = Connect(server_name, database_name)
If Connected Then
' If connected run query and disconnect
Call Query(SQL)
Call Disconnect
Else
' Couldn't connect
MsgBox "Could Not Connect!"
End If
End Sub
But when I run the macro, it's showing a runtime error
Invalid column name ALO0000274
Here ALO0000274 is the filter I set in A1.
Kindly help to fix this error.
Add quotes to your where clause (you're passing a text value, so you need to include quotes):
SQL = "SELECT Segmentation_ID,MPG,SUM(Segmentation_Percent) AS PERC " & _
"FROM dbo.HFM_ALLOCATION_RATIO " & _
"WHERE Segmentation_ID = '" & Sheets("Perc").Range("A1").Value & "' " & _
"GROUP BY Segmentation_ID,MPG ORDER BY MPG"
(Note the single quotes ' that enclose the value you want to filter)
I don't see where you are adding your single quotes around your string. Have you tried changing your WHERE clause portion of your SQL statement to "WHERE Segmentation_ID = '" & Sheets("Perc").Range("A1").Value & "' "

Access 2010 VBA Too few parameters: Expected 3

In VBA for Access 2010 and I am just trying to insert some data into a subform. I have a form, with 3 subforms on it. I have 3 unbound text boxes that the user will enter data, hit a command button, and then that data will instert into the subform I have on the layout. Here is my code:
Private Sub cmdAssign_Click()
CurrentDb.Execute " INSERT INTO Crew " _
& "(txtCrewName,txtKitNumber,txtActionDate) VALUES " _
& "(txtAssignCrew, txtAssignKit, txtAssignDate);"
End Sub
I know it has got to be something simple but I'm not really familiar with this. The txtCrewName, txtKitNumber, and txtActionDate are the empty values in the subform where I want data to go. And the txtAssignCrew, txtAssignKit, and txtAssignDate are the unbounds on the form, but outside of the subform 'Crew'. Any ideas? Thanks
EDIT: Figured it out. Thank you all for the help
So txtAssignCrew, txtAssignKit, and txtAssignDate are the names of controls on the form. The db engine doesn't know what they are, so assumes they must be parameters.
You could build those controls' values (instead of the controls' names) into your INSERT statement. But consider an actual parameter query instead, and execute it from a QueryDef object.
Dim db As DAO.Database
Dim qdf As DAO.QueryDef
Dim strInsert As String
strInsert = "PARAMETERS crew_name Text(255), kit_num Long, action_date DateTime;" & vbCrLf & _
"INSERT INTO Crew (txtCrewName,txtKitNumber,txtActionDate)" & vbCrLf & _
"VALUES (crew_name, kit_num, action_date);"
Debug.Print "strInsert:" & vbCrLf & strInsert
Set db = CurrentDb
Set qdf = db.CreateQueryDef("", strInsert)
qdf.Parameters("crew_name") = Me.txtAssignCrew
qdf.Parameters("kit_num") = Me.txtAssignKit
qdf.Parameters("action_date") = Me.txtAssignDate
qdf.Execute dbFailOnError
Set qdf = Nothing
Set db = Nothing
Note, in the PARAMETERS clause I assumed text as the data type for txtCrewName, long integer for txtKitNumber, and Date/Time for txtActionDate. If all are text, adjust the PARAMETERS clause.
This should work, assuming txtAssignCrew, Kit, and Date are your unbound controls you want to insert. Realize that if there are single quotes or anything in those fields, it would cause the statement to fail, so you would need to escape them.
Private Sub cmdAssign_Click()
CurrentDb.Execute " INSERT INTO Crew " _
& "(txtCrewName,txtKitNumber,txtActionDate) VALUES " _
& "('" & me.txtAssignCrew & "', '" & me.txtAssignKit & "','" & me.txtAssignDate & ");"
End Sub
I may have botched a quote.
Corrected code:
CurrentDb.Execute " INSERT INTO Crew " _
& "(txtCrewName,txtKitNumber,txtActionDate) VALUES " _
& "('" & txtAssignCrew & "','" & txtAssignKit & "','" & txtAssignDate & ");"
Notes:
- You might need to change the format for the AssignDate parameter
- Column names in the database are usually not prefixed with txt
- You would be better off using parametized queries to avoid SQL injection attacks

Access VBA - Identifying text

Im trying to create a button to delete certain records in a subform. However im getting "syntax error (missing operator) in query expression 'KEY_ID="1'.
I know what the problem is: The attribute is text therefore the value needs to be surrounded by single quotes. I just don't know how to write the VBA to accomplish this.
Private Sub cmdDelete_Click()
If Not (Me.subKey.Form.Recordset.EOF And Me.subKey.Form.Recordset.BOF) Then
If MsgBox("Confirm Deletion?", vbYesNo) = vbYes Then
Dim strSql As String
strSql = "DELETE FROM KEYS" & _
" WHERE KEY_ID='" & Me.subKey.Form.Recordset.Fields("KEY_ID")
Debug.Print strSql ' <- prints to Immediate window
CurrentDb.Execute strSql, dbFailOnError
End If
End If
strSql = "DELETE FROM KEYS" & _
" WHERE KEY_ID='" & Me.subKey.Form.Recordset.Fields("KEY_ID") & "'"
... though, mind you, using the quote as an ASCII character is safer, or at least more versatile or portable, when these kinds of things get more intensive.
strSql = "DELETE FROM KEYS" & _
" WHERE KEY_ID=" & _
Chr(32) & Me.subKey.Form.Recordset.Fields("KEY_ID") & Chr(32)
I'm not sure it's Chr(32) but I think that is correct.