Auto Populate Access Form using simple VBA code by setting a variable - ms-access

I was recently given the task of creating a form that will autofill with the information from a table. The information the form autofills is selected using a primary key called ModID. I have a combo box that has a List of the ModIDs that are listed as Active.
SELECT ModID
FROM P_Review
WHERE Status = "Active"
Simple enough. I then have VBA code running on the event After Update. So after the value for the combo box is select or changed it will run this VBA code.
Option Compare Database
Option Explicit
Private Sub selectModID_AfterUpdate()
'Find the record that matches the control.
On Error GoTo ProcError
Dim rs As Object
Set rs = Me.RecordsetClone
With rs
.FindFirst "ModID=" & Me.selectModID
If Not .NoMatch Then
Me.Bookmark = .Bookmark
Else
DoCmd.RunCommand acCmdRecordsGoToNew
Me!localModID = Me.selectModID.Column(0)
End If
End With
ExitProc:
Exit Sub
ProcError:
MsgBox "Error: " & Err.Number & ". " & Err.Description
Resume ExitProc
End Sub
The code runs fine (I get no errors when I debug or run).
Now for the access text box. I would like to populate certain fields based off the variable localModID. I have a dlookup in a text box to find the information in the table P_Review.
=DLookUp("Threshold","P_Review","ModID =" & [localModID])
So the DlookUp should find the value for the column threshold, in the table P_Review, where the ModID in P_Review equals the localModID set in the VBA code. But when I go to form view and select a ModID I get the Error 3070: The Microsoft Access database engine does not recognize as a valid field name or expression. I did copy this code from another database we are already using but it fails in this new instance.

Private Sub ModID_AfterUpdate()
Dim rs As Object
Set rs = Me.RecordsetClone
With rs
.FindFirst "ModID='" & Me.ModID & "'"
If Not .NoMatch Then
Me.Bookmark = .Bookmark
Else
DoCmd.GoToRecord , , acNewRec
Me!ModID = Me.ModID
End If
End With
End Sub
This is the answer to question. I used this code to auto update.

Try
Forms!<whatever_this_form_name_is>![localModID]
in your DLOOKUP

Related

MS Access Recordset Moving on Search even if no match found?

This is driving me nuts. I have an access VBA form where I want to allow users to type a document number into a box in order to jump directly to that record.
The underlying table as a field "DocNum", and the number is always sequential. I want the searchbox to display the current Doc Number the user is on, if they type in a different number and hit enter, it should either jump to that record if it exists, or if it doesn't exist, stay on the current record.
I'm trying to accomplish thisby having a hidden textbox bound to "DocNum", and an unbound visible box on top of it. On Form_Current() the unbound box is made to match the underlying field. After, update I run the following code to perform the search.
Private Sub txt_DocNumSearch_AfterUpdate()
Dim rs As Object
Set rs = Me.RecordsetClone
With rs
rs.FindFirst "[DocNum] = " & Str(Me![txt_DocNumSearch])
If rs.NoMatch Then
MsgBox "Record not found."
GoTo Cleanup
Else
Me.Bookmark = rs.Bookmark
Exit Sub
End If
End With
Cleanup:
rs.Close
Set rs = Nothing
Set dbs = Nothing
End Sub
What's driving me insane is that even when it doesn't find a match.... it skips to the next record anyway. No matter what I do... move last, trying to bookmark before I even search, etc... I can't get it to not jump forward. What am I missing?
Try simplifying it:
Private Sub txt_DocNumSearch_AfterUpdate()
Dim rs As DAO.Recordset
Set rs = Me.RecordsetClone
With rs
.FindFirst "[DocNum] = " & Str(Me![txt_DocNumSearch])
If .NoMatch Then
MsgBox "Record not found."
Else
Me.Bookmark = .Bookmark
End If
.Close
End With
End Sub

How to record unbound control to a database

I have a form control (address) that uses Dlookup to call info from a table "database" but the form is bound to table "Tracker". The dlookup is based on another control on the same form - "Name" I need the form to record this dlookup control, along with other controls that are bound to "tracker" as new recordto the table "tracker."
My failed attempts:
Using the default value property to assign the recalled data from the dlookup to another text box which would be bound to "tracker" This simply does not work for some reason. Perhaps I am missing something that tells this control "Address" to update upon selecting the correct "name?"
Code:
Private Sub SubmitReferral_Click()
On Error GoTo Err_SubmitReferral_Click
DoCmd.GoToRecord , , acNewRec
Exit_SubmitReferral_Click:
Exit Sub
Err_SubmitReferral_Click:
MsgBox Err.Description
Resume Exit_SubmitReferral_Click
End Sub
I also tried this - to assign the data - but the data from the dlookup in control "Address1" is not transferring/copying to control "Address2"
Private Sub Combo276_OnUpdate()
OnUpdate ([Address2].Value = [Address1].Value)
End Sub
Help or suggestions?
PS - I have tried to Edit per request to be as specific as possible, and to follow proper board etiquette.
Still unsure of your field names, etc., but the following is an example you can modify. Change 'tblEmployee' to 'database'.
I must state that if you are just starting out with developing in Access (or VBA) that you should never use names that are reserved words, or that can be misleading. Your table named 'database' is ok if named 'tblDatabase'.
Option Compare Database
option Explicit
Private Sub cmdInsert_Click()
Dim strSQL As String
Dim i As Integer
Debug.Print "cmdInsert; "
i = MsgBox("Do you want to add 1 row for Employee ID: " & Me.EmpID & " to table 'tracker'?", vbYesNo, "Confirm Add")
If i = vbNo Then
Exit Sub
End If
DoCmd.SetWarnings True
strSQL = "INSERT INTO tracker ( FirstName, LastName, Add1, City, St, Zip ) " & _
"SELECT tblEmployee.FirstName, tblEmployee.LastName, tblEmployee.Add1, tblEmployee.City, tblEmployee.St, tblEmployee.Zip " & _
"FROM tblEmployee " & _
"WHERE (((tblEmployee.EmpID)=" & Me.EmpID & "));"
DoCmd.RunSQL strSQL
End Sub
Thanks for the help - I solved my concern by hiding the fields that contain the dlookup, and putting code behind a button that copies the information to fields that are bound and therefore will record to the table "tracker"

Deleting Record in MS Access Form With Button

Recently started learning Access and I'm a bit stuck on deleting records within a form. I have a list with the following code:
Private Sub lstPickList_AfterUpdate()
Dim rst As DAO.Recordset
Set rst = Me.RecordsetClone
rst.FindFirst "OrderID=" & lstPickList.Column(0) & ""
If rst.NoMatch Then
MsgBox "The selected record can not be displayed." _
& "To display this record, you must first turn off record filtering.", _
vbInformation
Else
Me.Bookmark = rst.Bookmark
End If
Set rst = Nothing
End Sub
And a button that I would like to use to delete whatever Order is currently selected on the list. The "DeleteRecord" macro just gives me a "The command or action 'DeleteRecord' isn't available now." error. Searching has given me a bunch of code that hasn't worked for me at all.
You can delete directly from the clone:
If rst.NoMatch Then
MsgBox "The selected record can not be displayed." _
& "To display this record, you must first turn off record filtering.", _
vbInformation
Else
rst.Delete
End If

Microsoft Access Sub Form Write Conflict Troubles

I have a form which contains a subform which displays editable fields linked to one my tables. For a project I'm currently working on, one of the requirements is that I have to track when the last change was made to a record and who did so.
So what I've done is for each editable textbox or combobox within the form and subform I've made it so they have events on their BeforeUpdate and AfterUpdate events.
For example my BeforeUpdate for a textbox:
Private Sub textbox_BeforeUpdate(Cancel As Integer)
If Not isValidUser Then
Cancel = True
Me.textbox.Undo
End If
End Sub
and my AfterUpdate is:
Private Sub textbox_AfterUpdate()
updateRecord Me.textbox.Value, UserNameWindows
End Sub
and updateRecord is:
Public Sub updateRecord(bucNumber As String, updater As String)
Dim Dbs As Object
Dim rst As Object
Dim fldEnumerator As Object
Dim fldColumns As Object
sqlStatement = "SELECT fName " & _
"FROM t_Staff " & _
"WHERE uName='" & updater & "';"
'Getting fullname of user via username
Set rst = CurrentDb.OpenRecordset(sqlStatement)
'Setting fullname to updater variable
updater = rst(0)
'Clean Up
Set rst = Nothing
'Opening Bucket Contents
Set Dbs = CurrentDb
Set rst = Dbs.OpenRecordset("Bucket Contents")
Set fldColumns = rst.Fields
'Scan the records from beginning to each
While Not rst.EOF
'Check the current column
For Each fldEnumerator In rst.Fields
'If the column is named Bucket No
If fldEnumerator.Name = "Bucket No" Then
'If the Bucket No of the current record is the same as bucketNumber
If fldEnumerator.Value = bucNumber Then
'Then change the updated fields by updater and todays date
rst.Edit
rst("Last Updated By").Value = updater
rst("Last Updated On").Value = Date
rst.Update
End If
End If
Next
'Move to the next record and continue the same approach
rst.MoveNext
Wend
'Clean Up
Set rst = Nothing
Set Dbs = Nothing
End Sub
Okay now is the weird thing, this works totally fine when I make a modification to a control within the Main form, however as soon as a try to alter something in the subform it throws up a write conflict.
If I opt to save record it ignores my code for updating who last modified it and when and if I opt to discard the change it runs my code and updates it that it has been changed!
Anyone know what is wrong or of a better way to do this?

Possible to set filter on subform from parent form before subform data loads

I have frmParentForm with multiple controls used to build a filter for frmSubForm.
On frmParentForm_Load, I am doing (simplified example):
Me.sbfInvoice_List.Form.filter = "[created_on] >= #" & Me.RecentOrderDateCutoff & "#"
Me.sbfInvoice_List.Form.FilterOn = True
The problem is, on initial load, it seems the subform load is occurring first, so the entire table is loaded.
Is there a way (in a different event perhaps) to properly set the subform filter from the parent form so it is applied before the subform does its initial data load? (The subform can exist on its own, or as a child of many different parent forms (sometimes filtered, sometimes not), so I'd rather not put some complicated hack in the subform itself to accomplish this.)
Because the subform loads before the parent form, the parent form can not set a subform filter before the subform initially loads.
If you want to use the subform flexibly (all records when stand alone, but different subsets of records when included on different parent forms), I think you have to modify the subform to do it.
Private Sub Form_Open(Cancel As Integer)
Dim strParent As String
Dim strMsg As String
On Error GoTo ErrorHandler
strParent = Me.Parent.Name
Select Case strParent
Case "frmYourParentForm"
'set filter to only records from today '
Me.Filter = "[created_on] >= #" & Date() & "#"
Me.FilterOn = True
Case "frmSomeOtherParent"
'do something else '
End Select
ExitHere:
On Error GoTo 0
Exit Sub
ErrorHandler:
Select Case Err.Number
Case 2452
'The expression you entered has an invalid reference to '
'the Parent property. '
Resume Next
Case Else
strMsg = "Error " & Err.Number & " (" & Err.Description _
& ") in procedure Form_Open"
MsgBox strMsg
End Select
GoTo ExitHere
End Sub
Edit: If you want to track the sequence of events in the parent form and subform, you can add procedures like this one to the forms' modules.
Private Sub Form_Load()
Debug.Print Me.Name & ": Form_Load"
End Sub
Here is what I get when tracking the Open and Load events for my parent form and subform.
fsubChild: Form_Open
fsubChild: Form_Load
frmParent: Form_Open
frmParent: Form_Load