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

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

Related

Move to another record via combobox doesn't work in some circumstances

I have two forms: ‘frmClient’, (which has a subform that lists applicants), and ‘frmDisclosure’, which shows details of applicants. On frmClient there is a command button that opens a specified record in frmDisclosure. The procedure is Private Sub Command10_Click() - see below. This works.
The problem is that once in frmDisclosure via frmClient, it is not possible to move to another record. The procedure for opening another record in frmDiscloure is in a combobox control: Private Sub ComboFind_AfterUpdate().
This normally works, but it never works if frmDiscloure has been opened via frmClient. I have tried ‘requery’ and ‘refresh’ in various situations, and have tried closing frmClient once frmDisclosure is open. None of this works. If I want to get to a different record, the only solution I have at present is to close frmDisclosure and reopen it.
\\\\\\\\\\\\\\\\\\\\\\\\\\\\
Private Sub Command10_Click()
If NumForms > 0 Then
DoCmd.OpenForm "frmDisclosure"
Forms!frmDisclosure.FilterOn = False
DoCmd.OpenForm "frmDisclosure", acNormal, "", "[DiscPK]=" & Me.DiscPK, , acNormal
Else
DisplayMessage ("No form ref for this application.")
Exit Sub
End If
End Sub
\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\
\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\
Private Sub ComboFind_AfterUpdate()
Dim rs As Object
Set rs = Me.RecordsetClone
rs.FindFirst "[DiscPK] = " & Str(Nz(Me![ComboFind], 0))
If Not rs.EOF Then Me.Bookmark = rs.Bookmark
End Sub
\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\
frmDisclosure is opened to a single record, there are no other records to navigate. The RecordsetClone has only one record, so of course code won't find any others. Turn off the filter first:
Private Sub ComboFind_AfterUpdate()
Me.FilterOn = False
With Me.RecordsetClone
.FindFirst "[DiscPK] = " & Nz(Me.ComboFind, 0)
If Not .NoMatch Then Me.Bookmark = .Bookmark
End With
End Sub
As you can see, declaring and setting a recordset object variable is not required. .EOF would probably work just as well, I have just always used NoMatch. This will set focus to record, not filter the form.
If you prefer to display single record, then set the Filter property.
Private Sub ComboFind_AfterUpdate()
Me.Filter = "DiscPK=" & Nz(Me.ComboFind, 0)
End Sub

Access - Duplicate Record button creates a blank record

I've got a fairly simple database, 5000 records about 60-70 fields, and I created a button to copy the current record and blank out some of the fields (which we called EXPAND).
I recently received a requests to do the same thing without blanking out any fields but it doesn't work. I used the Command Button wizard on my form and chose the Duplicate option, but the new record is completely blank. Additionally, I get an error message when I close the record that talks about "A large amount of data copied to the clipboard". I tried the original button I had made (EXPAND) and it resulted in the same issue. Searching back through old records, I see that it was working as recently as 6/10/2016 (10 days ago).
Has something changed which would prevent this code from executing properly? Is there a new setting/option I need to enable to get it working again? Or is there some alternative method I can use to accomplish the same result?
Here is the (very simple) code the system created to duplicate the record (which doesn't work):
Private Sub cmdDuplicate_Click()
On Error GoTo Err_cmdDuplicate_Click
DoCmd.RunCommand acCmdSelectRecord
DoCmd.RunCommand acCmdCopy
DoCmd.RunCommand acCmdRecordsGoToNew
DoCmd.RunCommand acCmdSelectRecord
DoCmd.RunCommand acCmdPaste
Exit_cmdDuplicate_Click:
Exit Sub
Err_cmdDuplicate_Click:
MsgBox Err.Description
Resume Exit_cmdDuplicate_Click
End Sub
The fastest and simplest way is to use DAO and the RecordsetClone of the form:
Private Sub cmdDuplicate_Click()
Dim rstSource As DAO.Recordset
Dim rstInsert As DAO.Recordset
Dim fld As DAO.Field
If Me.NewRecord = True Then Exit Sub
Set rstInsert = Me.RecordsetClone
Set rstSource = rstInsert.Clone
With rstSource
If .RecordCount > 0 Then
' Go to the current record.
.Bookmark = Me.Bookmark
With rstInsert
.AddNew
For Each fld In rstSource.Fields
With fld
If .Attributes And dbAutoIncrField Then
' Skip Autonumber or GUID field.
ElseIf .Name = "SomeFieldToPreset"
rstInsert.Fields(.Name).Value = SomeValue
ElseIf .Name = "SomeFieldToExclude
' Leave blank
Else
' All other fields.
' Copy field content.
rstInsert.Fields(.Name).Value = .Value
End If
End With
Next
.Update
' Go to the new record and sync form.
.MoveLast
Me.Bookmark = .Bookmark
.Close
End With
End If
.Close
End With
Set rstInsert = Nothing
Set rstSource = Nothing
End Sub
I think the easiest way may to create an append query. Set the criteria field as the ID of the current record. This can be done pretty easily in the query design window.
No error message?
Do you have a Primary Key ID field on the form that doesn't allow you to copy duplicate ID?

Recordsetclone loop

The code below works BUT only to the first record in the continuous form its not looping threw the records. So if the first record is checked then I get the message "You need to select a RELEASE check box before proceeding." and if its not I get the other message.
What I need it to do is run down all the check boxes which is "ReleaseProduct" and exit sub at the first one it reaches if there is one and give a message and and if there isn't any check boxes checked run the Cancel = fncRequiredReleaseSelectedEmail(Me) and exit sub. Im messing up the loop somewhere...
Here is the code I have in my forms button....
Dim Cancel As Integer
Dim rs As Recordset
Set rs = Me.frmsub_ProductHoldData.Form.RecordsetClone
With rs
.MoveFirst
Do While Not .EOF
If rs.Fields("ReleaseProduct") = False Then
MsgBox "You need to select a RELEASE check box before proceeding.", vbInformation, "Selection Error"
Exit Sub
Else
Cancel = fncRequiredReleaseSelectedEmail(Me)
Exit Sub
End If
.MoveNext
Loop
End With
I'm having a hard time telling if this is exactly what you are looking for or not but this will look through all those records and only take action if one is checked.
The warning about selecting a Release check box only shows up if no boxes are checked.
Dim Cancel As Integer
Dim rs As Recordset
Set rs = Me.frmsub_ProductHoldData.Form.RecordsetClone
With rs
.MoveFirst
Do While Not .EOF
If rs.Fields("ReleaseProduct") = True Then
Cancel = fncRequiredReleaseSelectedEmail(Me)
Exit Sub
End If
.MoveNext
Loop
MsgBox "You need to select a RELEASE check box before proceeding.", vbInformation, "Selection Error"
End With

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

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

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?