How to exclude columns in Access VBA to maintain data - ms-access

I have a Access form with a bunch of buttons and some text boxes.
The text boxes automatically fill to the table. Thanks to someone else on here I figured out how to sync the button press to the fill the table. Now I need to ensure that the rest of information in the table stays when I press the button and the "Yes" get recorded. Currently all the other column of information doesnt record to the sheet but the button press does. How do I pass by those columns and keep their data and still record the various button presses that need to happen?
Thanks in advance!!
Below is the current button code that records on the table.
Private Sub CWTButton_Click()
Dim Sql As String
Sql = "INSERT INTO [Raw Data] (CWT) VALUES ('Yes');"
CurrentDb.Execute Sql
End Sub`
New Code
Private Sub CWTButton_Click()
Dim Sql As String
Sql = "INSERT INTO [RawData] ([Date], Staff, Species, Location, Length, Fish_ID, Comment, CWT) VALUES ('" & Me!Date.Value & "', '" & Me!Staff.Value & "', '" & Me!Species.Value & "', '" & Me!Location.Value & "', '" & Me!Length.Value & "', '" & Me!Fish_ID.Value & "','" & Me!Comment.Value & "','Yes');"
CurrentDb.Execute Sql
End Sub

New Code
Sql = "INSERT INTO [RawData] ([Date], Staff, Species, Location, Length, Fish_ID, Comment, CWT) VALUES (#" & Format(Me!Date.Value, "yyyy\/mm\/dd" & "#', '" & Me!Staff.Value & "', '" & Me!Species.Value & "', '" & Me!Location.Value & "', " & Me!Length.Value & ", " & Me!Fish_ID.Value & ",'" & Me!Comment.Value & "','Yes');"

Related

MS Access Tag property - how its identifying update and insert operation?

I trying to create Add,update,Delete operation on MS Access form.I found this code on internet where Insert and update is happening on the same button. I am not getting what is exactly happening in below line and how it's identifying it is for update or insert.
Not getting following line : = Me.txtid.Tag & "" = ""
Please find below code which works perfect as per requirement.
'When we click on button Add there are two options
'1. for insert
'2. for update
If Me.txtid.Tag & "" = "" Then
' this is for insert new
' add data in table
CurrentDb.Execute "insert into student(stdid,stdname,gender,phone,address)" & _
" values(" & Me.txtid & ",' " & Me.txtname & " ',' " & Me.cmbgender & " ','" & _
Me.txtphone & "', '" & Me.txtaddress & "')"
'refresh data in list on form
subform_student.Form.Requery
Else
CurrentDb.Execute "UPDATE student " & _
" set stdid = " & Me.txtid & _
", stdname = '" & Me.txtname & "' " & _
", gender = '" & Me.cmbgender & " ' " & _
", phone = ' " & Me.txtphone & " ' " & _
", address = ' " & Me.txtphone & " ' " & _
" WHERE stdid = " & Me.txtid.Tag
End If
The .Tag property is a general-purpose string property of every form and control object in VBA/VB6. It is provided as a place for developers to "put stuff" to support the operation of their applications.
The original code from which you copied your sample must have written a value to Me.txtid.Tag when the record was loaded (e.g., perhaps in the form's Current event) to indicate whether the record is an existing record or a new record (empty="new", non-empty="existing"). The line
If Me.txtid.Tag & "" = "" Then
simply checks to see if the .Tag property is empty, and then performs the INSERT or UPDATE accordingly.
BTW, re:
below code which works perfect as per requirement
No, it doesn't. Try adding a record where [stdname] is Tam O'Shanter and see for yourself. You should ditch the dynamic SQL and use one of
a bound form (as Gustav suggests),
a parameterized query, or
a recordset update.
Forget/remove all this code and bind the form to table Student to make this all happen automatically.
If a bound form is not familiar to you, browse for a tutorial for "Beginning with Microsoft Access" or the like.

Access, For Each loop to add multiple txtfields into table for each row in another table

My question might be confusing, I'm looking for a way to solve issue with 'maintenance' system written in Access.
There is a form with data, and I need to take txtFields values, listBox values and add them as sql row for each phone number that is stored in another table.
For example, dbShift contain few phone numbers (from 8 to 15) and they are switched each 8 hours.
When worker submit form with 'machine failure', maintenance office receives it thru access front-end.
This information need to be added in to another table as well, lets call it dbSMS, where we will store: nrMaszyny, nazwaMaszyny, Zglaszajacy, Przyczyna, Obszar, Telefon.
Now for each phone number stored in dbShift (numbers are switched by the form created for this table) this message needs to be duplicated.
It's all to automate process and send automatically SMS from the modem we have in the company, so maintenance employees will be informed right away about the issue, not only thru their workshop front end.
Everything seems to be done, but I'm stuck with the way of implementing that 'For Each' way to collect neccessary information and add them to table, where modem can feed the data to pass it thru SMS.
Maybe I'm wrong, maybe there is a better way for it than 'For Each'?
Any ideas?
dbShift:
ID, name, phoneNumber
dbSms:
nrMaszyny, nazwaMaszyny, Zglaszajacy, Przyczyna, Obszar, Telefon (data from FORM where worker sends machine failure form)
form from where You collect data:
Code of this form:
Option Compare Database
Private Sub buttonZamknijFormrularz_Click()
DoCmd.Close DoCmd.OpenForm "MainLoginForm"
Forms!MainLoginForm!txtPassword.Value = ""
End Sub
Private Sub cmdAdd_Click()
If IsNull(Me.listPrzyczyna) Or Me.listPrzyczyna = "" Then
MsgBox "Wybierz przyczynę awarii!", vbOKOnly, "Wymagane dane"
Me.listPrzyczyna.SetFocus
Else
Dim strSQL As String
strSQL = "INSERT INTO dbAwarieOtwarte (nrMaszyny, nazwaMaszyny, Zglaszajacy, dataZgloszenia, dataZakonczenia,
godzinaZgloszenia, Przyczyna, Obszar, Telefon, Komentarz) VALUES ('" &
Me!txtNrMaszyny & "', '" & Me!txtNazwa & "', '" & Me!txtZglaszajacy &
"', '" & Me!txtData & "', '" & Me!txtData & "', '" & Me!txtGodzina &
"', '" & Me!listPrzyczyna & "," & Me!txtNazwa & "," & Me!txtNrMaszyny
& "," & Me!txtObszar & "', '" & Me!txtObszar & "', '" & Me!txtTel &
"', '" & Me!txtKomentarz & "');"
DoCmd.SetWarnings False
DoCmd.RunSQL strSQL
DoCmd.SetWarnings True
DoCmd.Close ' DoCmd.OpenReport "repAwariaOtwarta", acViewPreview, , "ID=" & DMax("ID", "dbAwarieOtwarte")
End If
End Sub
Private Sub Polecenie35_Click()
DoCmd.Close DoCmd.OpenForm "formMaszynyObszar1"
End Sub
I suggest modifying your code to do something like the following... You said there is another table with phone numbers, so I will loop thru that table. Not sure if you want to use DAO or ADO, so I stuck with DAO.
Private Sub cmdAdd_Click()
Dim dbs as DAO.Database
Dim rsPhone as DAO.Recordset
If IsNull(Me.listPrzyczyna) Or Me.listPrzyczyna = "" Then
MsgBox "Wybierz przyczynę awarii!", vbOKOnly, "Wymagane dane"
Me.listPrzyczyna.SetFocus
Else
Dim strSQL As String
Set dbs = CurrentDB
Set rsPhone = dbs.OpenRecordset("<YourPhoneTable>")
Do While Not rsPhone.EOF
'<<< MAKE YOUR CHANGES TO GRAB THE PHONE NUMBER if needed for the following SQL
' 3/10/16 - changed SQL to add phonenumber to the insert.
strSQL = "INSERT INTO dbAwarieOtwarte (nrMaszyny, nazwaMaszyny, Zglaszajacy, dataZgloszenia, dataZakonczenia,
godzinaZgloszenia, Przyczyna, Obszar, Telefon, Komentarz, PhoneNumber) VALUES ('" &
Me!txtNrMaszyny & "', '" & Me!txtNazwa & "', '" & Me!txtZglaszajacy &
"', '" & Me!txtData & "', '" & Me!txtData & "', '" & Me!txtGodzina &
"', '" & Me!listPrzyczyna & "," & Me!txtNazwa & "," & Me!txtNrMaszyny
& "," & Me!txtObszar & "', '" & Me!txtObszar & "', '" & Me!txtTel &
"', '" & Me!txtKomentarz & "', '" & rsPhone!PhoneNumber & "');"
'DoCmd.SetWarnings False
dbs.Execute strSQL
'DoCmd.SetWarnings True
rsPhone.moveNext
Loop
rsPhone.Close
set rsPhone = Nothing
dbs.close
set dbs = Nothing
DoCmd.Close ' DoCmd.OpenReport "repAwariaOtwarta", acViewPreview, , "ID=" & DMax("ID", "dbAwarieOtwarte")
End If
End Sub

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

Combo box selection as text in string

I have a Form in Access which uses a selection from a combo box list to drive the creation of a report.
The combo box selection is evaluated as an ID. I need to get it as a text. I've found other similar issues but cannot get it to work. Can anyone walk me through it?
The closest thread I found was http://www.access-programmers.co.uk/...ad.php?t=58062, but not sure what "joining to the lookup table" entails.
In the code below, txtExpr1001, txtIndustry, and txtSkill are the combo boxes.
The code:
Private Sub cmdSubmit_Click()
Dim sWhereClause As String
sWhereClause = "Expr1001 = '" & txtExpr1001.Value & "' AND MonthsCon >= " & txtMonth1.Value & " AND IndustryName = '" & txtIndustryName.Value & "' AND MonthsNonCon >= " & txtMonth2.Value & " AND Skill = '" & txtSkill.Value & "' AND MonthsSkills >= " & txtMonth3.Value & ""
Call DoCmd.OpenReport("IndustryCon + IndustryNonCon + Skills", acViewPreview, , sWhereClause)
End Sub
My code does not trigger an error. The report opens but it's blank.
If you want to get the value of a combo box (which I'm not sure which of your .values are the combo box if any are) then you can just write something like this:
Private Sub cmdSubmit_Click()
Dim sWhereClause As String
'Me.Combo_BoxName.Column(0) is going to be how you call the combo box
'I put it right at the front of the string and chose ID as a random name as well
sWhereClause = "ID = '" Me.Combo_BoxName.Column(0) & "' AND Expr1001 = '" & txtExpr1001.Value & "' AND MonthsCon >= " & txtMonth1.Value & " AND IndustryName = '" & txtIndustryName.Value & "' AND MonthsNonCon >= " & txtMonth2.Value & " AND Skill = '" & txtSkill.Value & "' AND MonthsSkills >= " & txtMonth3.Value & ""
Call DoCmd.OpenReport("IndustryCon + IndustryNonCon + Skills", acViewPreview, , sWhereClause)
End Sub

inserting windows form data from text and combo boxes into mysql database

i am working on an application which will allow the user to add a company via the form. i a struggling on inserting the data into the MySQL DB in the INSERT query. the query is sound as it will work when directly applied, however the application won't commit...here is my code below...
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
sqlconnection.Close()
Dim com As New MySqlCommand("INSERT INTO companies VALUES(company_id, '" & TextBox1.Text & "', '" & RichTextBox1.Text & "', '" & TextBox4.Text & "', '" & TextBox5.Text & "', '" & ComboBox6.Text & "', '" & TextBox2.Text & "', '" & TextBox7.Text & "', '" & TextBox3.Text & "', '" & ComboBox2.Text & "', '" & RichTextBox3.Text & "', '" & ComboBox5.Text & "', '" & RichTextBox2.Text & "', '" & ComboBox7.Text & "', '" & ComboBox1.Text & "', '" & ComboBox4.Text & "';", con)
con.Open()
com.ExecuteNonQuery()
con.Close()
MsgBox("committed")
Thanks in advance
That's what you get for not using parametrized query.
Probably in one or more of your textboxes or richtextboxes an apostrophe causes your string concatenation to confuse everything.
Suppose that TextBox1 contains 'Acme's Inc.'. Now your string query text becomes
INSERT INTO companies VALUES (company_id, 'Acme's Inc.',
^
See the syntax error caused by blindly string concatenation?
I can't write a complete replacement of your code here because so many controls with undescriptive names. However you should write something like this
Dim cmdText = "INSERT INTO companies VALUES (#companyID, #param1, #param2, ....etc")
Dim com as New MySqlCommand(cmdText, con)
com.Parameters.AddWithValue("#companyID", company_id)
com.Parameters.AddWithValue("#param1", textbox1.Text)
.... 'and so on'
con.Open()
com.ExecuteNonQuery()
Apart from the quoting problem, correct representation of dates and decimal numbers for the underlying database system you have another big problem. SQL Injection (This is just an instructive link because SQL Injection is a very large topic)
So at the end
NEVER USE STRING CONCATENATION TO BUILD SQL QUERIES.