Access Table updating another Access Table based on variable fields - ms-access

I think my first submission might have been a bit confusing so I decided to rewrite it to better explain what I am attempting to do.
I have an Access database. In it there are two combo boxes, one containing all possible forms of annuity (that I'm dealing with) and the other combo box is the ones the user populates that apply to that particular client. This master list is fed from a table (tblPickAnnuityForms). This table has 3 fields, Name, VarName (these values match to another table), and Deleted (is a 1 or a 0 depending on if the user selected it). I also have a second table called tblPlanSpecs. This table, among other fields, has the fields that match up to the VarName field in the first table.
What I need to do, since tblPickAnnuityForms is basically a temporary table and it changes as you move between records (clients), is to repopulate it when you go to that record based on the values in tblPlanSpecs. Once tblPickAnnuityForms is populated based on the previous elections for this record (client), the two combo boxes are re-queried to display the proper values (ie the left box shows the remaining, unused annuity forms and the right box shows the forms that apply to this client.
Below is my attempt at doing this.
Dim db As DAO.Database
Dim rsList As DAO.Recordset
Dim rsData As DAO.Recordset
Dim CurrForm As String
Dim FormVal As Integer
Dim Plan As String
Set db = CurrentDb
Set rsList = db.OpenRecordset("tblPickAnnuityForms", dbOpenSnapshot)
Plan = [Forms]![FrmHome]![PlanNameCalc].Value
Set rsData = db.OpenRecordset("SELECT tblPlanSpecs.LifeAnnuity, tblPlanSpecs.FiveCC, tblPlanSpecs.TenCC, " _
& "tblPlanSpecs.FifteenCC, tblPlanSpecs.TwentyCC, tblPlanSpecs.FiveCertain, tblPlanSpecs.TenCertain, " _
& "tblPlanSpecs.FifteenCertain, tblPlanSpecs.TwentyCertain, tblPlanSpecs.FiftyJS, tblPlanSpecs.SixtySixJS, " _
& "tblPlanSpecs.SeventyFiveJS, tblPlanSpecs.HundredJS, tblPlanSpecs.MCR FROM tblPlanSpecs " _
& "WHERE tblPlanSpecs.PlanName='" & Plan & "'")
Do
CurrForm = rsList.Fields("VarName")
FormVal = rsData.Fields(CurrForm)
DoCmd.RunSQL ("UPDATE tblPickAnnuityForms " _
& "SET tblPickAnnuityForms.Deleted=" & rsData! & FormVal & " " _
& "WHERE (((tblPickAnnuityForms.VarName)='" & CurrForm & "'))")
MsgBox (CurrForm & "changed to " & FormVal)
rsList.MoveNext
Loop Until rsList.EOF
If Not rsList Is Nothing Then
rsList.CLOSE
Set rsList = Nothing
End If
If there is a better solution, perhaps I can go in a different direction. Currently this is bombing out in the loop where it says rsData! & FormVal It does not like using a variable to call a field. Ideally I would like to avoid specifically calling every variable by name in code when populating rsData. In other words, I want this to work no matter how many other options I add to my master list for the combo box, without going back in to add more items to select query.
Please let me know if I am unclear in my intended direction or methods. I could really use the help figuring out what is wrong.

Well, it seems I solved my own problem. I had so many ideas running through my head, I half-implemented one and forgot. The variable FormVal was already pulling the value I needed from rsData. I then tried to pull the value again using FormVal as the field variable. Anyway, below was the simple solution and everything works now.
DoCmd.RunSQL ("UPDATE tblPickAnnuityForms " _
& "SET tblPickAnnuityForms.Deleted=" & FormVal & " " _
& "WHERE (((tblPickAnnuityForms.VarName)='" & CurrForm & "'))")
In other words, I didn't need to do rsData![ & FormVal & ] (which I am sure is improper syntax) I just needed to use FormVal by itself.

Related

MS Access VBA Writing to a table from a form

I have a form (Purchase Orders) and a sub-form in it
(Purchase Order Details). The Main form contains Number of the
PO (text box), Supplier (combo-box), Employee (combo-box),
Status (combo-box) which contains 2 records (New and Done) and a date box (when the PO was created). The Sub-form (datasheet) contains Product (combo-box), Quantity and a Price field.
What I want to do is to add a button on the main form which will do
next.
When the button is pressed a VBA code should be executed and do next.
Take data from the Main form (Number of the PO, Status and the date)
and the Sub-form (Product, Quantity and Price) and put all that into
a table (StockMovements).
I managed to do that with the next code:
Private Sub cmdOrder_Click()
Dim strSQL As String
strSQL = "INSERT INTO StockMovement (ID_Product, Status, Quantity, ID_PurchaseOrder) VALUES (" & _
Me.frmPurchaseOrderDetails_Subform.Form!comboboxProduct & ", '" & _
Me!txtStatus & "', " & _
Me.frmPurchaseOrderDetails_Subform.Form!txtQuantity & ", " & _
Me!txtID_PurchaseOrder & ");"
DoCmd.RunSQL strSQL
Me.Requery
End Sub
However, there are 2 problems:
As you can see I didnt add the date field because I get an error,
cant remember which one it was exactly but I think 2075;
The code works without the date, but only adds one Product to the
table, the first one. And in a Purchase Order there are usually more
than one products.
Because Im totally new in VBA, I would kindly ask you to treat me like a newbie and explain more detailed, if possible.
(Fixed the code, forgot to change the language. I mean I pasted the wrong one, now its the right one but still not working of course :))
Thanks!
1) If you only have a problem with one specific field, I would check whats special with that one. Probably the input is formatted as a string and the field as Date/Time. In that case try to use the CDate()-Function. I could imagine, that a .Value at the end could solve the problem, too.
Dim datDate as Date
datDate = CDate(Me!txtDate.Value)
2) That your code inserts only one row is absoluterly correct. Remember that e.g. Me!txtStatus.Value is a textbox that contains only one single piece of data. The rows of data are saved in a table and depending on the row you have selected with a main-form (= one row), the corresponding value is shown in the textbox.
INSERT INTO table (field1,field2) VALUES (value1,value2)
An INSERT INTO inserts one row every time it's executed. So the SQL in the code you have mentioned needs to be repeated. You could do so using loops.
Dim strSQL As String
strSQL = ""
For Each Item In Group
strSQL = strSQL & "INSERT INTO table (field1,field2) VALUES (value1,value2)"
Next
In my opinion, copying data that way is absolutely annoying with VBA. You need to create recordsets, modify and merge them. I would try to solve as much as possible with Access Non-VBA-Solutions.
My question to you: Did you think about linking the form (and sub-form) directly to the table(s)?
The date can be inserted this way:
"INSERT INTO StockMovement ([DateField]) " & _
"VALUES (#" & Format(Me!DateField.Value, "yyyy\/mm\/dd") & "#)"
That said, your code will insert one record only. To insert multiple records you need a select query or - much faster - use DAO to open the target table as a recordset and then, as source, loop the RecordsetClone of your subform and copy the records to the target table one by one.

Update query in subform

I have a form where there is string input that is an input to a parameter in a query (insert sql injection joke here), and a subform that displays the query's results.
Currently the parameter is essentially someVar Like "*" & forms!myForm!input & "*", but since the user can enter more than one string (i.e. a sentence) what I really want is someVar Like "*firstWord*" or someVar Like "*secondWord*"... etc
Since the number of parameters varies, I need to programatically generate the query. Looping through the words in the input and dynamically generating the where statement is not too hard in VBA:
dim sc as variant
sc=split(myInput)
dim where as string
where=""
for c=0 to UBound(sc)
where = where & "like '*" & sc(c) & "*' or "
next
where = left(where, len(where) - 3)
dim qd as querydef
set qd=currentDb.querydefs("myQuery")
qd.sql="select var where " & where
[my subform].requery
However, when I update the query, the subform that displays its data does not update even though I tell it to requery. If I leave the form and reenter it has the correct data. My approach seems to be wrong. What would be a better way to approach this?
I would have "myQuery" saved as the base query without any where criteria. Then you could go with:
[my subform].RecordSource = "select * from myQuery where somevar like '*" & replace(myInput, " ", "*' or somevar like '*") & "*'"
[my subform].Requery
This does away with needing to loop through the words in the input string and picks up on Andre's suggestion of modifying the RecordSource for the subform rather than trying to modify the query that the RecordSource is pointing to.

multiple item lookup text box

i have created an access 2010 search box that filters results based on a column within a table and then presents me with the results based on query.
what i am trying to achieve is to be able to put not just one item at a time in the search box but multiple items.
this is for a whole estate of routers that i manage and every day i get a list of routers that need to be status checked so what i am doing now is copying and pasting each router name on the search box and it gives me the status, location and circuit ref but what i want to do i to copy and paste all of the router names in one go and get independent results for each router.
this is the code that i have applied for the filter in the text box:
Where Condition = [Circuit Reference] Like "*" & [Forms]![Query1]! [Text12] & "*"
i could add more text boxes and apply this filters to them but i would still have to copy and paste every router name independently.
i am not an access guru so appologies if this question is too easy to answer but i cant find anything on the web that helps me with my issue.
It sounds like you want multiple wildcard searches on the same field. You can do this by using OR in your SQL query.
Dim strSearchConditions As String
Dim strTerms() As String
Dim strSQL As String
Dim i as Integer
strSearchConditions = ""
strTerms = Split(Me.txtSearch,",") 'Assuming you separate your search terms with a comma
For i = 0 To UBound(strTerms)
If Not strTerms(i) = "" Then
strSearchConditions = " OR [Circuit Reference] Like '*" & strTerms(i) & "*'"
End If
Next i
If Not strSearchConditions = "" Then
strSQL = "Select * FROM tblMyTable WHERE 1=1 AND (" & strSearchConditions & ")"
Else
MsgBox "No search terms!"
End If

Access add new line to table

I have sub that runs when the database is opened to a specific form and I'm trying to get it to add information in a table.
The table name is UnAuthorizedAccess and the columns in table are ID(auto number), NAME(text), COMPUTERNAME(text), ATTEMPTDATE(date/time).
What commands do I need to use to add a new record to this table? I have a VBA that if they're login information Isn't there is will force close access all together. I'm trying to gather information on the user as well before kicking them out.
I figured this is the easiest way as outlook won't let you send a hidden email from the user unless they first see it.
You can add records to a recordset with the following code, but I am unsure whether you have a field called COMPUTERNAME. You shouldn't need to add the ID value as its an autonumber.
dim Rst as recordset
Set Rst = CurrentDb.OpenRecordset(Name:="UnauthorizedAccess", Type:=RecordsetTypeEnum.dbOpenDynaset)
With Rst
.AddNew
![NAME] = Me.Name.Value
![COMPUTERNAME] = Me.COMPUTERNAME.Value
![ATEMPTDATE] = date()
.Update
End With
As for sending hidden emails, see this question I asked not so long ago. It sends an email via outlook, but remember to reference the Microsoft Outlook Object library in the VBA Editor.
CurrentDB.Execute is the method for executing SQL statements, and INSERT INTO is the SQL statement for adding records to a DB table.
CurrentDB.Execute "INSERT INTO UnAuthorizedAccess (NAME, COMPUTERNAME, ATTEMPTDATE) " & _
"VALUES (" & Your_NAME_Variable & ", " & Your_COMPUTERNAME_Variable & ", " & Now() & ")
Replace Your_NAME_Variable and Your_COMPUTERNAME_Variable with the variables in your code containing these values.

MS Access 2013 copy a specific number of fields and paste into a new record

I have found similar answers to this question, even on this site, however, the syntax has not worked for my database and I'm not sure what needs to be done. This data base is used to house audits for staff performance and accuracy. I am now in the midst of creating the forms and getting them to flow properly for the user.
When conducting an audit, the user will need to enter six specific fields into the first form. Those forms are Audit, Month, Year, Username, Location, Reviewer, and Date. The user will need to complete multiple audits, however, these six fields will always be the same.
I would like to copy these fields in the first form and carry them into the second form so the user does not have to repeat the information. Here is my current code (set to run on the click of a command button on the bottom of screen 1):
Dim strSQL As String
strSQL = "INSERT INTO [tblTripMem] (Audit, Month, Year, Username, Location, Reviewer, Date)"
strSQL = strSQL & " Values (" & Me.cboFP1Audit & "," & Me.Month & "," & Me.Year & "," & Me.Username & "," & Me.Location & "," & Me.Reviewer & "," & Me.Date & ") FROM [FPScreen1]"
strSQL = strSQL & "WHERE (currentrecord = " & Me.CurrentRecord & ")"
DoCmd.RunSQL (strSQL)
Each time I run this I receive the following error: "Invalid SQL statement; expected 'DELETE', 'INSERT', 'PROCEDURE', 'SELECT', or 'UPDATE'.
I am new to Access and am unsure of what this means or how to fix it. All I know is that I'm not finding a solution. Can anyone help? I'd greatly appreciate it.
Here's a mock-up Access file illustrating a way to do what you're doing without using SQL:
With Form 1 open...
...complete the various fields:
Click the Copy to Form 2 button and this will open Form 2 and populate its fields with the data from Form 1:
Here's the VBA code on the Copy to Form 2 button's OnClick event:
Private Sub cmdCopyToFrm2_Click()
Dim frm As Form
DoCmd.OpenForm "Form2"
Set frm = Forms!Form2
With frm
!AuditRef = Me.cboFP1Audit
!AuditMonth = Me.txtAuditMonth
!AuditYear = Me.txtAuditYear
!AuditUsername = Me.txtAuditUsername
!Location = Me.txtLocation
!Reviewer = Me.txtReviewer
!AuditDate = Me.txtAuditDate
End With
End Sub
Note that when Form 2 opens, the textbox that the cursor defaults to might not seem to show any data; if you move away from that textbox it should magically show (don't know why it does this, but there you go).
INSERT INTO table (...) VALUES (...) cannot have a FROM or WHERE clause. You insert a single record with fixed values, not data from another table.
But once you delete these clauses, you will have other errors, because you need to format your string and date values correctly to get the INSERT query to work.
And then you will still be prone to SQL injection errors. It is safer to use Recordset.AddNew and .Update to add records.
See e.g. here: https://stackoverflow.com/a/34969410/3820271
(but without the loop)