Listbox in Ms access - ms-access

I can store records in the DB by using combobox with the following code.
Here single part number is selected and partnumber related data is stored in the DB table.
But I want the code for Listbox...When I select multiple partnumbers ..how can I store in the DB table?
Case "Pn ADDED to Wrapper", _
"Pn REMOVED from Wrapper"
If Me!PartNumber <> "All" And Me!PartNumber <> "Select" Then ' a proper part number has been selected in combo box
strNewSq5 = _
"INSERT INTO tblTmpEventLog (TrackingNumber,PartNumber,PartNumberChgLvl,EnteredBy,EventTypeSelected,EventDate)"
strNewSq5 = strNewSq5 & " VALUES ('" & tempTrackingNumber & "','" & _
tempPartNumber & "','" & _
tempPartNumberChgLvl & "','" & _
tempEnteredBy & "','" & _
tempEventTypeSelected & "'," & _
"#" & Forms!frmEventLog_Input.EventDate & "#)"
dbs.Execute strNewSq5, dbFailOnError
TrnsfTmpEventToEventLog
Else
displayMsgBox = MsgBox("A single part number must be specified. Please correct.", vbCritical, "System Error")
Exit Sub
End If

You need to iterate over the selected items and store them one by one:
MS Access 2007 - Cycling through values in a list box to grab id's for a SQL statement
EDIT re comment
You do not provide sufficient information for a detailed answer, but here are some notes that may help.
For Each itm In Me.NameOfListBox.ItemsSelected
If Instr("All,Select",Me.NameOfListBox.Column(0, itm) )=0 Then
'' a proper part number has been selected in list box
'' Me.NameOfListBox.Column(0, itm) is the column (zero in this example
'' and row (itm) of the selected item in the list box. If it is the
'' part number, then you might like to say:
'' tempPartNumber = Me.NameOfListBox.Column(0, itm)
strNewSq5 = "INSERT INTO tblTmpEventLog " & _
"(TrackingNumber,PartNumber,PartNumberChgLvl,EnteredBy," & _
"EventTypeSelected,EventDate)"
strNewSq5 = strNewSq5 & " VALUES ('" & tempTrackingNumber & "','" & _
tempPartNumber & "','" & _
tempPartNumberChgLvl & "','" & _
tempEnteredBy & "','" & _
tempEventTypeSelected & "'," & _
"#" & Forms!frmEventLog_Input.EventDate & "#)"
dbs.Execute strNewSq5, dbFailOnError
TrnsfTmpEventToEventLog
Else
''Do not insert
End If
Next

Related

Syntax error in number using query expression in MS-Access

I got Syntax error in number using query expression? error while I run below code
CurrentDb.Execute "UPDATE StateBudget " & _
" Set S_ID='" & Me.cbState & "'" & _
", C_ID=" & Me.cbCategory & _
", Year='" & Me.cbYear & "'" & _
", 1=" & Me.Ctl1 & _
", 2=" & Me.Ctl2 & _
", 3=" & Me.Ctl3 & _
" WHERE S_ID = """ & _
DLookup("ID", "States", "State='" & _
Me.subformStateBudget.Form.Recordset.Fields("State") & "'") & """"
S_ID and Year are Text fields, C_ID and the rest 1,2,3 are Number fields.
If there anything I missed? I am a beginner in programming so...
Probably one of number Me.* fields is null, so SQL will have syntax error. Use Nz function for such kind arguments. For debugging create SQL in string variable before executing and dump content of this variable to Immediate window using Debug.Print. You will see the problem easily.
Dim strSQL
strSQL = "UPDATE StateBudget " & _
" Set S_ID='" & Me.cbState & "'" & _
", C_ID=" & Nz(Me.cbCategory, 0) & _
", Year='" & Me.cbYear & "'" & _
", 1=" & Nz(Me.Ctl1, 0) & _
", 2=" & Nz(Me.Ctl2, 0) & _
", 3=" & Nz(Me.Ctl3, 0) & _
" WHERE S_ID = """ & _
DLookup("ID", "States", "State='" & _
Me.subformStateBudget.Form.Recordset.Fields("State") & "'") & """"
Debug.Print strSQL
CurrentDb.Execute strSQL, dbFailOnError

INSERT INTO table with Foreign Key from Form

I am trying to create a Form that is used to manually enter data in certain scenarios. Most data is input from CSV files which is working fine. I have 4 tables, Part , Assembly , MachineOrder , and Job. I was able to write code for entering into the base table, Part, from the Form no problem. The issue now is entering data into the Assembly and MachineOrder tables where the Parts are being referenced by their PID autonumber field and the Assemblies are being referenced by their AID autonumbered field. I have tried many different kinds of methods to perform this of which you can see a bit of in my commented out code. What is there is what I believe to be my closest to correct code thus far with the error now being that Access asks me for the parameter value of rPID even though it is finding the value in the Dlookup function fine. I'm assuming the same is true for the rAID section as well.
Otherwise I'm getting errors of Key Violations when using the INSERT then UPDATE method you see commented out.
The form is called HOTEntry
Any advice on what my problem may be is greatly appreciated, I'm a student and this is my first time trying to use what I've learned in a professional application so any and all constructive criticism is wanted! Apologies if this is a rather specific question but I could really use the help on this since I've been working on it for two days to no avail...
My code:
Sub HOTParts2()
Dim rPID As Integer
Dim rAID As Integer
Dim dbs As DAO.Database
Dim sqlstr1 As String
Dim sqlstr2 As String
Dim sqlstr3 As String
Dim sqlstr4 As String
Set dbs = CurrentDb
'sqlstr1 = "INSERT INTO Assembly ( PID, ModelNum, ModelRev, ModelDescription ) " _
' & "SELECT (PID,Forms!HOTEntry!txtHotModel, Forms!HOTEntry!txtHotRev, Forms!HOTEntry!txtHotDes)" _
' & "FROM Part " _
' & "WHERE Part.PartName = Forms!HOTEntry!txtPartName AND Part.Config = Forms!HOTEntry!txtConfigEntry AND Part.Rev = Forms!HOTEntry!txtRevEntry"
sqlstr1 = "INSERT INTO Assembly ( ModelNum, ModelRev, ModelDescription,PID ) " _
& "VALUES (Forms!HOTEntry!txtHotModel, Forms!HOTEntry!txtHotRev, Forms!HOTEntry!txtHotDes," & "rPID" & ");"
'
'sqlstr2 = "UPDATE Assembly " _
' & "SET PID =" & rPID & " " _
' & "WHERE Assembly.ModelNum = Forms!HOTEntry!txtHotModel And Assembly.ModelDescription = Forms!HOTEntry!txtHotDes And Assembly.ModelRev = Forms!HOTEntry!txtHotRev;"
'
'sqlstr3 = "INSERT INTO MachineOrder ( AID, Serial, CustName ) " _
' & "SELECT (AID,Forms!HOTEntry!txtHotSerial, Forms!HOTEntry!txtHotCust)" _
' & "FROM Assembly" _
' & "WHERE Assembly.Model=Forms!HOTEntry!txtHotModel And ModelDescription= Forms!HOTEntry!txtHotDes And ModelRev = Forms!HOTEntry!txtHotRev; "
sqlstr3 = "INSERT INTO MachineOrder (Serial, CustName, AID ) " _
& "VALUES (Forms!HOTEntry!txtHotSerial, Forms!HOTEntry!txtHotCust," & "rAID" & ");"
'
'sqlstr4 = "UPDATE MachineOrder " _
' & "SET AID =" & rAID & " " _
' & "WHERE AID IS NULL;"
rPID = DLookup("PID", "Part", "PartName = " & "'" & Forms!HOTEntry!txtPartName & "'" & " And " & "Config = " & "'" & Forms!HOTEntry!txtConfigEntry & "'" & " And " & "Rev = " & "'" & Forms!HOTEntry!txtRevEntry & "'")
DoCmd.RunSQL sqlstr1
'DoCmd.RunSQL sqlstr2
rAID = DLookup("AID", "Assembly", "ModelNum = " & "'" & Forms!HOTEntry!txtHotModel & "'" & " And " & "ModelDescription = " & "'" & Forms!HOTEntry!txtHotDes & "'" & " And " & "ModelRev = " & "'" & Forms!HOTEntry!txtHotRev & "'")
DoCmd.RunSQL sqlstr3
'DoCmd.RunSQL sqlstr4
End Sub
Well, if you want to use the looked up rPID and rAID in a query, you need to do more than just set them in VBA. You can either manually fill them in in your SQL statement, use a parameter and a QueryDef and fill in the parameter in your QueryDef, or put the DLookUp inside your SQL statement.
Going with the first approach here, only unquoted rPID in your initial statement, and put it after rPID was set.:
rPID = DLookup("PID", "Part", "PartName = " & "'" & Forms!HOTEntry!txtPartName & "'" & " And " & "Config = " & "'" & Forms!HOTEntry!txtConfigEntry & "'" & " And " & "Rev = " & "'" & Forms!HOTEntry!txtRevEntry & "'")
sqlstr1 = "INSERT INTO Assembly ( ModelNum, ModelRev, ModelDescription,PID ) " _
& "VALUES (Forms!HOTEntry!txtHotModel, Forms!HOTEntry!txtHotRev, Forms!HOTEntry!txtHotDes," & rPID & ");"
DoCmd.RunSQL sqlstr1

CheckIfExist. If exist don't insert the data, if not insert the data

I have a problem on how to insert data into two different table. So my requirements is this.
Under Group Details, The user need to click all the needed information on the dropdown menu and input on the textbox of the table grid view before clicking the ADD Link, after this the page will load displaying the Added Job Title and business group details. The user is allowed to input as many Job title as the user want.
I already finished the table but I have problems in saving the data that I input.
So my first table looks like this Before
and I edit it and this is my table Now
So my problem is this, in my database i have two table. One is EMPGROUP_TBL with columns SEQID, masterID, Business Unit, Division, Sub-Division etc. and the other is EMP_MASTERTBL with columns MasterID, Name, LastName, Jobtitle.
Now everytime I click Add link the jobtitle will not be able to save in the EMP_MASTERTBL so I create a code in VB.Net that will update the EMP_MASTERTBL table when I click the add button under Group Details.
Here's my codes.
If UpdateInsDelRecord("INSERT INTO EMPGROUP_TBL (MASTERID, BUSINESS_UNIT, " & _
"DIVISION, SUB_DIVISION, CLASSIFICATION, SUB_CLASSIFICATION) VALUES " & _
"('" & HandleQuote(Me.lblval_Empid.Text) & "', " & _
"'" & Me.ddl_BusinessUnit.SelectedValue.ToString() & "' ," & _
"'" & val_division & "' ," & _
"'" & val_subdivision & "' ," & _
"'" & Me.ddl_Classification.SelectedValue.ToString() & "' ," & _
"'" & Me.ddl_SubClassification.SelectedValue.ToString() & "')" & _
";" & _
"UPDATE EMP_MASTERTBL SET JOBTITLE = '" & Me.txtJobtitle.Text & "' " & _
"WHERE MASTERID = '" & Me.lblval_Empid.Text & "'") = True Then
Return True
Response.Redirect("eHR_EmpMaintenance.aspx")
Else
Return False
End If
But the user must be able to add as many as Jobtitle and EMPGROUP_TBL details as the user want. So I'm thinking that I'll just write another query for that? How can I add the Group Details and be able to add as many as Jobtitle as the user want?
CheckIfExist
I figured maybe I could use the CheckIfExist and if the employee has an existing data to the jobtitle, business unit, division, sub-division, classification and sub-classification similar to the one that you will add, the messagebox will show that the data already exist. If no data found then it will be able to add the details under the employee's group details. And if you input similar jobtitle but different business unit etc. the data will just be updated and vice versa.
Here's what my code for this.
Function SaveUserGroup() As Boolean
Try
Dim jobtitle As String = Me.txtJobtitle.Text
Dim businessunit As String = Me.ddl_BusinessUnit.SelectedValue
Dim division As String = Me.ddl_Division.SelectedValue
Dim subdivision As String = Me.ddl_SubDivision.SelectedValue
Dim classification As String = Me.ddl_Classification.SelectedValue
Dim subclassification As String = Me.ddl_SubClassification.SelectedValue
Dim CheckMasterTblIfExist As Boolean
Dim CheckGroupTblIfExist As Boolean
Dim insrtResult As Boolean
Dim seqid As String = Me.lblSEQID.Text
Dim emp_id As String = Request.QueryString("emp_id")
If jobtitle <> "" And businessunit <> "Please Select" And division <> "Please Select" And subdivision <> "Please Select" And classification <> "Please Select" And subclassification <> "Please Select" Then
CheckMasterTblIfExist = CheckRecord("SELECT MASTERID, JOBTITLE FROM EMP_MASTERTBL WHERE JOBTITLE = '" & jobtitle & "' AND MASTERID = '" & emp_id & "' ")
CheckGroupTblIfExist = CheckRecord("SELECT * FROM EMPGROUP_TBL WHERE BUSINESS_UNIT = '" & businessunit & "' AND DIVISION = '" & division & "' AND SUB_DIVISION = '" & subdivision & "' AND CLASSIFICATION = '" & classification & "' AND SUB_CLASSIFICATION = '" & subclassification & "' AND MASTERID = '" & emp_id & "' AND SEQID = '" & seqid & "'")
If Not CheckMasterTblIfExist And CheckGroupTblIfExist Then
insrtResult = UpdateInsDelRecord("UPDATE EMP_MASTERTBL SET JOBTITLE = '" & jobtitle & "' " & _
"WHERE MASTERID = '" + Me.lblval_Empid.Text + "'" & _
";" & _
"INSERT INTO EMPGROUP_TBL(MASTERID, BUSINESS_UNIT, " & _
"DIVISION, SUB_DIVISION, CLASSIFICATION, SUB_CLASSIFICATION) VALUES " & _
"('" & HandleQuote(Me.lblval_Empid.Text) & "', " & _
"'" & businessunit & "' ," & _
"'" & division & "' ," & _
"'" & subdivision & "' ," & _
"'" & classification & "' ," & _
"'" & subclassification & "')")
If Not insrtResult Then
MessageBox("alert('Error Ocurred While Inserting a Data.')")
Else
MessageBox("alert('Successfully Added.')")
End If
Else
MessageBox("alert('Data Already Exist.')")
End If
End If
Catch ex As Exception
MessageBox("Error Ocurred while Inserting a data")
Throw
End Try
End Function
I haven't been completed the code yet. I'm in the adding if there's no data and my problem is that the messagebox keeps on telling me that the data already exist even if there's still no employee's group details that added. Please help me with this.
begin tran
if exists (select * from table with (updlock,serializable) where key = #key)
begin
update table set ...
where key = #key
end
else
begin
insert into table (key, ...)
values (#key, ...)
end
commit tran
you can use like this

Check if Exist or Not then Insert Update

I need to check if the data exist if the data didn't exist then I'll be able to insert and update but if the data exist the messagebox will show that the data already exist but when I tried to add same data that already exist it still add and no messagebox shown that it already exist.
here's my code
If jobtitle <> "" And businessunit <> "Please Select" And division <> "Please Select" And subdivision <> "Please Select" And classification <> "Please Select" And subclassification <> "Please Select" Then
insrtResult = UpdateInsDelRecord("UPDATE EMP_MASTERTBL SET JOBTITLE = '" & jobtitle & "' " & _
"WHERE MASTERID = '" & empID & "'" & _
";" & _
"INSERT INTO EMPGROUP_TBL(MASTERID, BUSINESS_UNIT, " & _
"DIVISION, SUB_DIVISION, CLASSIFICATION, SUB_CLASSIFICATION) VALUES " & _
"('" & HandleQuote(empID) & "', " & _
"'" & businessunit & "' ," & _
"'" & division & "' ," & _
"'" & subdivision & "' ," & _
"'" & classification & "' ," & _
"'" & subclassification & "')")
If Not insrtResult Then
MessageBox("alert('Error Ocurred While Inserting a Data.')")
Else
MessageBox("alert('Successfully Added.')")
End If
Else
MessageBox("alert('Data Already Exist.')")
End If
what could be the problem to my code? Thanks in advance.
For SQL Server check the MERGE query, i used this to perform an "upsert" on my own db, it also seems to be performing fast enough.
You can chose a condition and perform different operations whether it returns true or false (e.g. if ID already exists then update, else insert)
For MySql i think there are solutions much more easier to write, wich unfortunatly i can't remember at the moment
https://msdn.microsoft.com/en-us/library/bb510625.aspx

Insert Into Statement VBA [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 7 years ago.
Improve this question
Hi everyone I am coding in VBA using Access 2013 I wrote my code two different ways and keep getting a syntax error. Here's my code.
Private Sub cmdAdd_Click()
CurrentDb.Execute "INSERT INTO GroupVolunteers(Group, Leader, Name,
phone, email, EmergencyContact, EmergencyContact) " & _
" VALUES(" & Me.txtGroup & "','" & Me.cboLeader & "','" & Me.txtName & "','"
& Me.txtEmail & "','" & Me.txtPhone & "','" & Me.txtEmergencyContact & "','"
& Me.EmergencyNumber & "','" & Me.txtRegNumber & "')"
'clear form
cmdClear_Click
'refresh data in list on form
frmStudentSub.Form.Requery
End Sub
OR
'when we click on button Add there are two options
'1. for insert
'2. for update
If Me.txtRegNumber & "" = "" Then
'this is for insert new
'add data to table
CurrentDb.Execute "INSERT INTO GroupVolunteers(Group, Leader, Name,
phone, email, EmergencyContact, EmergencyContact) " & _
" VALUES(" & Me.txtGroup & "','" & Me.cboLeader & "','" &
Me.txtName & "','" & _
Me.txtEmail & "','" & Me.txtPhone & "','" &
Me.txtEmergencyContact & "','" & Me.EmergencyNumber & "','" &_
Me.txtRegNumber & "')"
Else
'otherwise (Tag of txtID store the id of student to be modified)
CurrentDb.Execute "UPDATE GroupVolunteers " & _
" SET Group=" & Me.txtGroup & _
", leader='" & Me.cboLeader & "'" & _
", name='" & Me.txtName & "'" & _
", email='" & Me.txtEmail & "'" & _
", phone='" & Me.txtPhone & "'" & _
", EmergencyContact='" & Me.txtEmergencyContact & "'" & _
", EmergencyNumber='" & Me.txtEmergencyNumber & "'" & _
", NumberVolunteers ='" & Me.txtNumberVolunteers & "'" & _
" WHERE RegNumber = " & Me.txtRegNumber.Tag
" VALUES(" & Me.txtGroup & "', ...
Think of how that's going to end up in your statement:
VALUES(<Me.txtGroup>', ...
In other words, you're either missing the opening quote for a character-type column or you have too many for a numeric-type column. It should be one of:
" VALUES('" & Me.txtGroup & "', ... // for character-type column
" VALUES(" & Me.txtGroup & ", ... // for numeric-type column
That should fix your insert in both code blocks, you may also want to examine the update in the second code block as well. It has no quotes on the group column which is okay if it's numeric-type but probably not if it's character-type.