How to load a multiline recordset into an Access form with VBA - vba

I'm runing a query (which is returning the correct data) but how can I loop the recordset and add each line in the form with VBA? Because it's currently adding the last line repeatedly.
Private Sub buscarReservasFio()
Dim strSQL As String
strSQL = "SELECT * FROM tblReservasFio WHERE fk_solicitacao = " & "'" & arrParameters(0) & "'"
Set db = CurrentDb
Set rs = db.OpenRecordset(strSQL, dbOpenDynaset, dbSeeChanges)
If rs.BOF Or rs.EOF Then
'to-do insert
MsgBox ("Insert")
Else
Do Until rs.EOF
DoCmd.GoToRecord , , acNewRec
Me.ds_funcao = rs.Fields("ds_funcao").Value
Me.fk_titulo = rs.Fields("fk_titulo").Value
Me.nr_cor = rs.Fields("nr_cor").Value
Me.nr_peso = rs.Fields("nr_peso").Value
Me.dt_liberacao = rs.Fields("dt_liberacao").Value
Me.dt_baixa = rs.Fields("dt_baixa").Value
rs.MoveNext
Loop
End If
rs.Close
db.Close
Set rs = Nothing
Set db = Nothing
End Sub

Apparently, form is bound to table but your code is populating UNBOUND controls. That's the only way I can replicate your output - which should be expected. The reason multiple rows of same data show is because controls (BOUND or UNBOUND) repeat for each record and since there is only one set of controls, the same data shows in UNBOUND controls for all rows - last record from recordset loop. Step debug and watch data change on form. The GoToRecord action is meaningless because no data is input to BOUND controls. The result is same without that line.
In order to display multiple records from table, bind controls to fields. Then, options to modify nr_peso field with new calculated value when form first opens:
run an UPDATE action SQL
open a recordset of form's RecordsetClone and loop through that recordset and change value of nr_peso field - changes in RecordsetClone will immediately reflect in the form
code physically moves to each record on form and modifies field value

Related

Form event procedure not moving to last record

I am experiencing some odd behavior from a form I am creating in an access database. I have a form called frmSeedling with a subform called frmSeedling detail. frmSeedling gets launched by an event procedure from a command button on a separate form called frmTransect. The OpenArgs passes the primary key of frmTransect called Transect_OID to frmSeedling. Transect_OID is the link field between frmSeedling and frmSeedlingDetail. I have a Form_Current event procedure in frmSeedling to count the number of unique entries on frmSeedling, and create a custom unique id called Seedling_OID. The tables that are the record source for these forms are linked ODBC tables. Below is the code:
Private Sub Form_Current()
Dim rs As DAO.Recordset
Set rs = Me.RecordsetClone
If Not (rs.EOF) Then
rs.MoveLast
End If
Set rs = Nothing
If IsNull(Seedling_OID) Then
Entry_No = Nz(DCount("Seedling_OID", "rd_Seedling", "Transect_OID = '" & Me.Transect_OID & "'"), 0) + 1
Seedling_OID = Transect_OID & "SD" & Entry_No
End If
End Sub
However, when I launch frmSeedling from frmTransect, I get an error saying I am trying to overwrite the primary key. When I look at the form, this is happening because somehow Access is try to create a new record at the beginning of the form instead of the end of the form, thus thinking that the unique Id I have: created has already been used. Here is a screenshot to show what I mean:
What is curious is that with a separate form called frmDWD with subform frmDWDdetail, I have used this exact setup and it worked fine. Here is the code from frmDWDdetail:
Private Sub Form_Current()
Dim rs As DAO.Recordset
Set rs = Me.RecordsetClone
If Not (rs.EOF) Then
rs.MoveLast
End If
Set rs = Nothing
If IsNull(DWD_OID) Then
DWD_Piece = Nz(DCount("DWD_OID", "rd_DWD", "Transect_OID = '" & Me.Transect_OID & "'"), 0) + 1
DWD_OID = Transect_OID & "W" & DWD_Piece
End If
End Sub
And here is what that looks like:
Notice how in frmDWD, the record being edited is the last record in the form, while in frmSeedling it is trying to edit the first record in the form. I have set all of the data properties exactly the same in both form and subform, and at least to my eye the code looks identical. Any SQL reasons why I am getting this behavior? Any ideas for fixes? Thanks!!
After hours of playing "Which-of-these-things-is-not-like-the-other" I discovered that the issue was in the property sheet of the subform. I switched "Filter on Empty Master" from "Yes" to "No" and that solved my issue.
You are not using the recordset for anything, so try this reduced code:
Private Sub Form_Current()
Dim Entry_No As Long
If IsNull(Me!Seedling_OID.Value) Then
Entry_No = Nz(DCount("*", "rd_Seedling", "Transect_OID = '" & Me!Transect_OID.Value & "'"), 0) + 1
Me!Seedling_OID.Value = Me!Transect_OID.Value & "SD" & Entry_No
End If
End Sub

How to stop records from being overwritten on close

When I close the form, the current record overwrites the first record in the table. If I include "Me.Undo" just before closing the form then the data on the form is changed but not in the underlying table. How can I stop both of these from happening?
Private Sub Form_Load()
Dim strSelect As String
strSelect = "SELECT * FROM tblData ORDER BY tblData.txtName;"
Set dbs = CurrentDb()
Set rst = dbs.OpenRecordset(strSelect, dbOpenDynaset)
rst.MoveFirst
Me.txtName = rst!txtName
Private Sub btnClose_Click()
'Me.Undo
MsgBox " "
DoCmd.Close acForm, "frmdata", acSaveNo
I would like to form to just close without displaying another record and without overwriting another record in the table.
It is quite possible that your Form has it's DataSource property set to 'tblData'.
So after you Form loads, the Form_Load() event fires, and you modify the first Record of the Table that is set in the Form's DataSource property.
This is the line that modify's the Form data: Me.txtName = rst!txtName

Query error on a recordset.update vba line

I am trying to print multiple labels for multiple records. The number of labels is consistent for any one run of the label report and all labels for the same record need to be together on the printed sheet. Parameters are entered on TakeNoticeForm and once a button is clicked a recordset, rsQuery, is created with TakeNoticeLabelQuery. Another recordset is created, rsTable, based on a table, TemporaryTNLabels. This table is a copy of my main table, Certificates, without data. I'm using nested For loops to parse through the query results and add "x" copies of said record into the temp table, which will then be used to print the labels. Once the labels are printed the data will be cleared from the temp table for use again later.
Everything I have so far appears to work until I actually start adding data to my temp table. I get Error 3991 - "The query failed to execute because the identifier '[Certificates].[TownshipID]' could not be found" and it points to .Update. [TownshipID] is a lookup field in the Certificates table that was the original for TemporaryTNLabels. I tried to keep the copy intact for possible reuse with other reports but I don't need that field for this report so deleted the lookup field from the temp table to hopefully solve the problem. TakeNoticeLabelQuery is actually a copy of another query, TakeNoticeQuery, that did reference Township information. Again, I was hoping to reuse objects but made a copy and only kept what I needed, which has no reference to TownshipID.
After stripping everything unnecessary away, I can't figure out why it's still trying to find [TownshipID]. I'm still trying to wrap my head around recordsets so wondering if the problem is actually elsewhere, buty I'm confused as to how this error is even remotely related to my code. Any help is appreciated. The SQL for the query and code for generating label data are below.
SELECT Certificates.DatabaseID, Certificates.CertCounty, Certificates.TaxYear, Certificates.ParcelNumber, Certificates.MailToFirstName, Certificates.MailToLastName, Certificates.MailToAlso, Certificates.MailToCity, Certificates.MailToState, Certificates.MailToZip
FROM Counties INNER JOIN Certificates ON Counties.ID = Certificates.CertCounty
WHERE (((Certificates.DatabaseID) Between ([Forms]![TakeNoticeForm]![FirstDBTextbox]) And ([Forms]![TakeNoticeForm]![LastDBTextbox])) AND ((Certificates.CertCounty) Like [Forms]![TakeNoticeForm]![CountyCombobox] & '*') AND ((Certificates.TaxYear) Like [Forms]![TakeNoticeForm]![TaxYearTextbox] & '*')) OR (((Certificates.CertCounty) Like [Forms]![TakeNoticeForm]![CountyCombobox] & '*') AND ((Certificates.TaxYear) Like [Forms]![TakeNoticeForm]![TaxYearTextbox] & '*') AND ((IsNull([Forms]![TakeNoticeForm]![FirstDBTextbox]))<>False) AND ((IsNull([Forms]![TakeNoticeForm]![LastDBTextbox]))<>False));
Option Compare Database
Option Explicit
Private Sub TNLabelPreviewButton_Click()
Dim iTab As Integer
Dim iLabel As Integer
Dim numLabels As Integer
Dim totalRecords As Long
Dim db As DAO.Database
Dim qdf As DAO.QueryDef
Dim rsTable As DAO.Recordset
Dim rsQuery As DAO.Recordset
' Set query definition for creating recordset
Set db = CurrentDb()
Set qdf = db.QueryDefs("TakeNoticeLabelQuery")
If CurrentProject.AllForms("TakeNoticeForm").IsLoaded Then
qdf.Parameters("[Forms]![TakeNoticeForm]![FirstDBTextbox]") = [Forms]![TakeNoticeForm]![FirstDBTextbox]
qdf.Parameters("[Forms]![TakeNoticeForm]![LastDBTextbox]") = [Forms]![TakeNoticeForm]![LastDBTextbox]
qdf.Parameters("[Forms]![TakeNoticeForm]![CountyCombobox]") = [Forms]![TakeNoticeForm]![CountyCombobox]
qdf.Parameters("[Forms]![TakeNoticeForm]![TaxYearTextbox]") = [Forms]![TakeNoticeForm]![TaxYearTextbox]
' qdf.Parameters("[Forms]![TakeNoticeForm]![TakeNoticeDateTextbox]") = [Forms]![TakeNoticeForm]![TakeNoticeDateTextbox]
Else
qdf.Parameters("[Forms]![TakeNoticeForm]![FirstDBTextbox]") = ""
qdf.Parameters("[Forms]![TakeNoticeForm]![LastDBTextbox]") = ""
qdf.Parameters("[Forms]![TakeNoticeForm]![CountyCombobox]") = ""
qdf.Parameters("[Forms]![TakeNoticeForm]![TaxYearTextbox]") = ""
' qdf.Parameters("[Forms]![TakeNoticeForm]![TakeNoticeDateTextbox]") = CStr(Date)
End If
Set rsQuery = qdf.OpenRecordset
rsQuery.MoveLast
totalRecords = rsQuery.RecordCount
'Close and delete records from TemporaryTNLabels table.
DoCmd.SetWarnings False
DoCmd.Close acTable, "TemporaryTNLabels"
DoCmd.RunSQL "DELETE FROM [TemporaryTNLabels]"
DoCmd.SetWarnings True
numLabels = Me.NumLabelsTextbox
MsgBox numLabels & " labels"
'Open a table-type Recordset
Set rsTable = db.OpenRecordset("TemporaryTNLabels", dbOpenTable)
rsQuery.MoveFirst
With rsTable
For iTab = 1 To totalRecords
For iLabel = 1 To numLabels
Debug.Print rsQuery!DatabaseID
.AddNew
!ParcelNumber = rsQuery!ParcelNumber
.Update ' <-------------------------This is where the error points.
.Bookmark = .LastModified
Next iLabel
rsQuery.MoveNext
Next iTab
End With
' DoCmd.OpenReport ReportName:="TakeNoticeLabelReport", View:=acViewPreview
rsTable.Close
Set rsQuery = Nothing
Set qdf = Nothing
Set db = Nothing
End Sub
This is why I stopped using lookup fields :-( I would delete the table TemporaryTNLabels or rename it to TemporaryTNLabels_OLD. Then recreate the table TemporaryTNLabels from scratch with only one field ParcelNumber, and start from there.

How can I uncheck an entire column of checkboxes?

How can I uncheck an entire column of checkboxes?
I have a field in each record in my access table that has a checkbox, as time goes on I check boxes, but at the end to reset I would like to put a button on the split form that will uncheck all of the boxes.
It is the second field "Acct" on the table "tblData1" and I want to control it from the form "frmMain" Using a button "cmdResetAcct"
Thank you in advance!
Run an UPDATE query.
CurrentDb.Execute "UPDATE tblData1 SET Acct = False WHERE Acct <> False"
The WHERE clause makes it more efficient because only the checked rows are written.
You can use the recordset you already have directly in the OnClick event of your button:
Dim rs As DAO.Recordset
Set rs = Me.RecordsetClone
If rs.RecordCount > 0 Then
rs.MoveFirst
End If
While Not rs.EOF
If rs!Acct.Value = True Then
rs.Edit
rs!Acct.Value = False
rs.Update
End If
rs.MoveNext
Wend
Set rs = Nothing
This is very fast, and your form will update instantly.

Showing some rows in textboxes on a Form using vba

I have a query that returns for example 5 rows, I want to show thes these rows(fields) in textboxes. but it only shows me one record. I have also set Default view Property of my form into Continuous form. her is my code:
Private Sub List2_DblClick(Cancel As Integer)
Dim rst As DAO.Recordset
Set rst = CurrentDb.OpenRecordset("SELECT XValue, YValue,Wert FROM tb_DCM_Daten WHERE (FzgID=" & Forms!frm_fahrzeug!ID & " AND [Name]='" & List2.Value & "')")
If rst.RecordCount <> 0 Then
Do While Not rst.EOF
Text8.SetFocus
Text8.Text = rst.Fields("XValue").Value
Text10.SetFocus
Text10.Text = rst.Fields("YValue").Value
Text11.SetFocus
Text11.Text = rst.Fields("Wert").Value
rst.MoveNext
Loop
End If
End Sub
how can I do that?
As it stands now, your code would loop through the Recordset, put the values from the first record into the textboxes, then overwrite those values with the ones from the second record, and overwrite those with the values from the third record, and so on.
It sounds like you want a subform. Have a look at the Office tutorial here for more information.