Why do I get Run-time Error 91 in this MS Access code? - vba

So, I have a MS Access database application. In this application is a main form, which contains a number of subforms. One form in particular has a drop down box that I populate with dates from a database query. When one of these dates is selected, I run a subroutine that is supposed to update a recordset on the subform with history information. Below is some edited code (just removed the large number of fields from the queries)
Private Sub pickdate_AfterUpdate()
'''''''''''''''''''''''''''''''''''''''''
' Add review history by selected date
'''''''''''''''''''''''''''''''''''''''''
Dim rs As Recordset
Set rs = CurrentDb.OpenRecordset("SELECT model, entered_date FROM history WHERE entered_date=#" & Me.pickdate.value & "# ORDER BY model DESC", dbOpenDynaset, dbSeeChanges)
If rs.BOF = False Then rs.MoveFirst
While rs.EOF = False
Forms!main!histories.Form.Recordset.AddNew
Forms!main!histories.Form.Recordset![model] = rs![model]
Forms!main!histories.Form.Recordset![entered_date] = rs![entered_date]
Forms!main!histories.Form.Recordset.Update
rs.MoveNext
Wend
End Sub
I get the error on the Forms!main!histories.Form.Recordset.AddNew line.
I have tried the following versions of that line:
Forms!main!histories.Form.Recordset.AddNew
main!histories.Form.Recordset.AddNew
histories.Form.Recordset.AddNew
Me.Form.Recordset.AddNew
Me.Recordset.AddNew
Me.AddNew
Me.main!histories.Form.Recordset.AddNew
Me!histories.Form.Recordset.Addnew
Me!main!histories.Form.Recordset.AddNew
I am literally at my wit's end trying to figure out where the issue is.
The subform has all the proper boxes to store the information. I have given them labels to match their database columns that will go into them. I've tried setting their control sources to the database column names and not setting them to anything. I've looked up a hundred different "solutions", none of which seem to either fit the problem or work.
I feel like I am overlooking something really easy.

I reckon you have problems with your names. Check all of them. Do not forget that a subform consists of two parts, the subform control and the form contained. These often have the same name, but not always. In the code you are using, you must have the name of the subform control, not the form contained. If entering data into the subform manually is not working properly, your controls are not bound.
This works for me on a sample table.
Dim rs As Recordset
Set rs = CurrentDb.OpenRecordset("SELECT atext from table1 WHERE akey=21")
If rs.BOF = False Then rs.MoveFirst
While Not rs.EOF '= False
Me.Table1_subform1.Form.Recordset.AddNew
Me.Table1_subform1.Form.Recordset!AText = rs!AText
Me.Table1_subform1.Form.Recordset.Update
rs.MoveNext
Wend
To run a query you could say:
sSQL="INSERT INTO NameOfTable (model, entered_date) " _
& "SELECT model, entered_date FROM history WHERE entered_date=#" _
& Me.pickdate.value & "#"
CurrentDB.execute, dbfailOnError
You can check the sql works in the query design window.

Related

Refresh forms recordset source with custom SQL query keeping current selection after closing second form

I have 2 forms in MS Access. One is an overview form as an endless form, the other shows details of the single records.
The overview form gets its content by a custom SQL passthrough query on opening:
Dim strSQL As String
strSQL = "SELECT DISTINCT tbl_Parts.strPart, Title, Comment FROM [tbl_Parts] inner JOIN [tbl_PartModules] ON tbl_Parts.strPart = tbl_PartModules.strPart ORDER BY tbl_Parts.strPart DESC"
Dim qdf As DAO.QueryDef, rst As DAO.Recordset
Set qdf = CurrentDb.CreateQueryDef("")
Dim strTmpConnQDF As String
strTmpConnQDF = CStr(Application.TempVars("tempvar_StrCnxn"))
qdf.Connect = strTmpConnQDF
qdf.sql = strSQL
qdf.ReturnsRecords = True
Set rst = qdf.OpenRecordset
Set Forms![frm_PartsOverview].Recordset = rst
Forms![frm_PartsOverview].Requery
'No rst.Close to have the data still in the Form!
Set qdf = Nothing
Within that overview, buttons can be used to change the underlying SQL query to show different records.
Each record has a "show details" button in the endless form which opens the detail form.
Within the detail form, I can change the data of the underlying record. After closing this form, I want to keep all settings (record selection, SQL query data) that were before opening the detail form. But I also want to update the underlying data, showing the changes made in the detail form also on the overview form.
I tried this code with the "hide" button of the detail form, but this does not work:
Forms!frm_PartsDetail.Visible = False
Forms!frm_PartsOverview.Recalc
Forms!frm_PartsOverview.Refresh
Forms!frm_PartsOverview.Requery
I tried all three variants (Recalc, Frequery, Refresh) but none of them did the trick.
I guess its because of the way I assign the SQL query as the recordsource of the form.
But how to update the recordsource, keeping all settings like they were before entering the detail form?
Well, you can use a me.Refresh - that will (should) show updates to the form. (but, the fact of it being basedon a pt query probably will effect this. I suggest changing to a linked view - thus no pt query required and thus access can stay on the given row, and you can use a me.refresh. (with a PT query and you having assigned the forms data source "one time", then me.refresh is unlikely to work.
So, I suggest using a linked view for that form. (and performance will be just as good at the pt query - and your me.Refresh will work (to show any changes made to the table).
the other way? Grab the current row (PK) before you do the me.Requery. Then do a find first on the pk row, and jump back to the row in question.
So, ignoring you have a sub form etc.
Then this code:
Dim PK As Long
PK = Me!ID
Me.Requery
Dim rst As DAO.Recordset
Set rst = Me.Recordset
rst.FindFirst ("ID = " & PK)
However, as noted, if you base that form on a linked view, and not set the datasource as you do, then a me.Refresh will show any changes made, and also stay on that current row.
So, in your case, to re-calc, re-display, and show any updates, and return to current row you were on?
"air code warning"
Dim PK As Long
Dim f As Form
Dim rst As DAO.Recordset
Set f = Forms!frm_PartsDetail
PK = f!ID
f.Requery
Set rst = f.Recordset
rst.FindFirst ("ID = " & PK)

Can I open a recordset using application-level features (user-defined functions, form-based parameters) in Access?

I want users to be able to provide a query they made in the GUI, using a combo box, and then load that query into a recordset to do further processing on it. This fails if the query contains a user-defined function or form-based parameter.
My code looks like this:
Private Sub cmbSelectionColumn_AfterUpdate()
Dim r As DAO.Recordset
Set r = CurrentDb.OpenRecordset("SELECT DISTINCT " & EscapeSQLIdentifier(Me.cmbSelectionColumn.Value) & " FROM " & EscapeSQLIdentifier(Me.cmbSelectionTable.Value))
Do While Not r.EOF
'Do stuff
r.MoveNext
Loop
End Sub
Where cmbSelectionColumn is a user-selected column, and cmbSelectionTable is a user-selected table or query, and EscapeSQLIdentifier is a function that escapes and adds brackets to ensure the field and tablename are safe. This mostly works fine, but it fails in multiple cases, such as involving pass-through queries, user-defined functions, and form-based parameters.
Is there a way I can create a recordset from any query that works in Access, without having to worry about this?
Yes, there is, but you will have to do some trickery.
Forms support these queries just fine. And forms have a .RecordsetClone property that allows us to retrieve the recordset.
To allow us to retrieve the recordset from code, we're going to create a new blank form, and add a module to it (in fact, any form with a module will do). We'll name it frmBlank.
Then, we can adjust the code to use this form to retrieve the recordset.
Private Sub cmbSelectionColumn_AfterUpdate()
Dim r As DAO.Recordset
Dim frm As New Form_frmBlank
frm.RecordSource = "SELECT DISTINCT " & EscapeSQLIdentifier(Me.cmbSelectionColumn.Value) & " FROM " & EscapeSQLIdentifier(Me.cmbSelectionTable.Value)
Set r = frm.RecordsetClone
Do While Not r.EOF
'Do stuff
r.MoveNext
Loop
End Sub
This allows us to retrieve the recordset. The form will not pop up (since we haven't set .Visible to True), and will close once the code is done running since there is no active reference to it. I haven't yet seen any tables or queries that do work in Access, but do not work with this approach, and the performance penalty is minor. It does make for odd code and an odd blank form with blank module that will cause your database to malfunction when deleted.
The following may present an alternative approach to opening DAO recordsets which reference form-based parameters:
Dim db As DAO.Database
Dim pr As DAO.Parameter
Set db = CurrentDb
With db.CreateQueryDef("", "SELECT DISTINCT " & EscapeSQLIdentifier(Me.cmbSelectionColumn.Value) & " FROM " & EscapeSQLIdentifier(Me.cmbSelectionTable.Value))
For Each pr In .Parameters
pr.Value = Eval(pr.Name)
Next pr
With .OpenRecordset
If Not .EOF Then
.MoveFirst
Do Until .EOF
' Do stuff
.MoveNext
Loop
End If
.Close
End With
End With
Here, since references to objects outside of the scope of the query (such as references to form controls) become query parameters whose parameter name matches the original reference, the parameter name is evaluated to yield the value held by the form control, and the parameter value is then updated to the result of this evaluation.

VBA in MS Access: how to accelerate a loop operation on a recordset

In a database under my maintenance (MS Access 2010) I use a VBA procedure for cleaning up records, concretely: setting values in a field from "yes" to "no". The procedure loops through all records and sets the values in the respective field as required.
My database has about 900 records so far. Not too many, one should think.
My problem: the VBA procedure operates very slowly. On my current machine I have to wait for about 10 seconds until the loop has gone through the 900 records. That's impractical in everyday work.
What I need: I am looking for ways to speed this up, either through improvements to the code, or through a completely different approach.
Here is my procedure:
Private Sub WipeSelectionMarks_Click()
'Remove any filter that might be set to reduce the number of records in
'the form - We want here to operate on all records in the database!
Me.Filter = ""
Me.FilterOn = False
'Don't know if we really need two commands here; but at least it works
'Operate on a recordset that holds all the records displayed in the form
Dim rs As DAO.Recordset
Set rs = Me.RecordsetClone
rs.MoveFirst
Do Until rs.EOF
With rs
.Edit
!Int_IwSelectMove = False
.Update
End With
rs.MoveNext
Loop
'Message box with info what has been done
MsgBox "A total of " & rs.RecordCount & " records were updated by wiping the Move mark"
'Cleaning up
Set rs = Nothing
Me.Refresh
End Sub
Note 1: if a solution would be using an SQL command instead, I will be grateful for practical hints or examples. I use SQL commands at many places, still, getting put on the right track here would be helpful.
Note 2: Or can the VBA procedure be rewritten in a way that only records where the field in question has value "yes" are processed (these are usually only 20-30 of the 900), and those with "no" are left out?
You can use the UPDATE command:
CurrentDb.Execute "UPDATE YourTable SET Int_IwSelectMove = False"
can the VBA procedure be rewritten in a way that only records where
the field in question has value "yes" are processed
Indeed, and that may very well be the fastest method, as you will not have to requery the form:
With rs
Do Until .EOF
If !Int_IwSelectMove.Value = True Then
.Edit
!Int_IwSelectMove = False
.Update
End If
.MoveNext
Loop
.Close
End With
Or you could use FindFirst or a filtered recordset. Running SQL on the recordset of a form is usually the last option.

MS Access - SetFocus on multiple text boxes to check if data exists via SQL

The problem I'm facing:
I try to check if inserted text from multiple text boxes is already existing in a table before saving the records to avoid duplicates.
I created a form to enter new members and save them into a table. The key to avoid duplicates is to check the combination of given name, last name and birth date with existing records. (It's most likely that there won't be two person with all three criteria matching)
I have no problem to check the existence for only one text box by setting the focus on the desired box and use the SQL query IF EXISTS...
But since I would need to set focus on several text boxes(IMO) the problem occurs.
Is there a way to set focus on multiple text boxes?
The idea would be to use an IF EXISTS...AND EXISTS statement and I would need to implement the .SetFocus statement for each text box before checking its existence.
I hope you get my point and I would be glad if someone could share some knowledge. :)
Thanks in advance
There seems to be some missing information in order to find the best solution to your problem. so the below response will be based on assumptions as to how your form is working.
I'm assuming you are using an unbound form with unbound text boxes? if this is the case, then you must have a button that is the trigger for checking/adding this information to your table. lets say your command button is called "Save". You can use the following code without the need to .setfocus to any textbox.
Private Sub Save_Click()
Dim db as DAO.Database
Dim rst as DAO.Recordset
Dim strSQL as string
set db = currentdb 'This is the connection to the current database
'This is the SQL string to query the data on your table
strsql = "SELECT * " & _
"FROM [Yourtablename] " & _
"WHERE ((([YourTableName].[FirstName]) ='" & me.FormFirstNameField & "' AND ([YourTableName].[LastName]) ='" & me.FormLastNameField & "' AND ([YourTableName].[DOB]) =#" & me.FormDOBField & "#));"
set rst = db.openrecordset(strsql) 'This opens the recordset
if rst.recordcount <> 0 then
'Enter code to inform user information already exists
else
'Enter code if information does not exits
end if
rst.close 'Closes the recordset
set rst = nothing 'Frees memory
set db = nothing 'Frees Memory
End Sub
Let me know if this code works or if I need to make changes based on your scenario.

Rookie SQL inside of VB question - MSAccess 2003

Hey guys, can anyone help me with a simple question. I have this SQL statement below in a sub in VB within access from a button click, and I am new to this.
Here is what I typed:
Private Sub Command0_Click()
Dim rs As Recordset
Dim sql As String
Dim db As Database
Set db = CurrentDb
sql = "SELECT * FROM Transactions"
Set rs = db.OpenRecordset(sql)
Do Until rs.EOF
rs.MoveNext
Loop
If Not rs.EOF Then
MsgBox "test"
End If
End Sub
Ok, so how do I populate this?? Essentially I am justing starting out with this, so I am wondering how do I take this simple code, and run it like a query so that the resulting recordset opens.
Thanks!
some other remarks and advices:
1) Always indicate which type of recordset you are using. Here it seems to be a DAO recordset, so go for a complete declaration like:
Dim rs as DAO.recordset
Runing on another computer, and depending on the declaration order of ADODB and DAO libraries, the very same code can generate a bug.
2) To avoid any disturbing error message if no record is available, you can add an extra test, something like
if rs.recordcount = 0 then
Else
rs.moveFirst
....
3) To browse the complete recordset with debug.print, you could do it this way. Just ad a 'm_debugLine' as string, and a 'fld' as DAO.Field in your declarations.
rs.MoveFirst
do while not rs.eof
m_debugLine = ""
for each fld in rs.fields
m_debugLine = m_debugLine + vbTab + fld.value
next fld
debug.print m_debugLine
rs.movenext
loop
4) you could even add a debug.print line to print out the field names before printing the data. I guess you'll find this one
Depending on what you are trying to do, you may be over-complicating this. A better approach would be to set the recordsource of the form (in the property sheet) to the transactions table then drop the fields you want on the form using the visual designer.
HOWEVER, If you really must do it this way, here is the code that will replace what you have and open a spreadsheet like view of the data in the transactions table.
Private Sub Command0_Click()
docmd.Opentable "transactions"
End Sub
If you want to limit the results to a query, then first build the query and save it then use the following code.
Private Sub Command0_Click()
docmd.OpenQuery "MyQueryName"
End Sub
To be extremely literal, your original code DID populate a recordset (in the rs object). You can access the fields by name using code in your while loop such as
debug.print rs("Field1")
You put your code inside the Do..Loop. This code will be evaluated for each record that is encountered.
Do Until rs.EOF
Msgbox "The value for MyField is " & rst!MyField
rs.MoveNext
Loop
you get at the columns of the record for the recordset like rs(0) or rs("columnname")....
if your transactions table has three columns named a, b, c you could get to it like:
rs(0)
rs(1)
rs(2)
or
rs("a")
rs("b")
rs("c")