Problem with RecordCount in MS-access 2010 VBA - vba

I am trying to understand what I have done wrong in the code snippet below. I am reading some session records with a specific Client ID and putting the records returned into LineGrid for further processing. The problem is with the line NoL = Rs.RecordCount The query returns multiple lines (I can see this in the development environment). So in one example NoL is assigned the value 1 even although Rs.Recordcount is larger (3). I can check this directly in the debug environment.
At risk of stating the obvious even is record count is 3 only the one row is inserted into LineGrid
Dim Db As DAO.Database
Dim RsCL As DAO.Recordset 'ClientSession
Dim NoL As Integer
Dim LineGrid As Variant
Set RsCL = Db.OpenRecordset("Select * From ClientSession WHERE ClientID = " & CDID)
If RsCL.EOF Then
MsgBox ("Nothing to Invoice")
Exit Sub
End If
'RsCL.MoveFirst
NoL = RsCL.RecordCount
LineGrid = RsCL.GetRows(NoL)
RsCL.Close
I have tried
Changing the data type of NoL to Long - No effect
Putting Rs.Count in the place of (NoL) in GetRows property - No effect
If I replace NoL with a value e.g. 100 then the code works fine then all records are loaded into LineGrid but I don't have the true record count.
I have tried moving the record pointer with .movefirst property ( you will note that line is currently commented out) - No effect
Ultimately I need LineGrid to contain the data from the table and NoL to have the true record count

When you open a recordset, not all of the records are loaded immediately. In order to force all of the records to load, you need to move to the last record before moving back to the first one:
RsCL.MoveLast
RsCL.MoveFirst
Regards,

Related

Runtime error 3164 for Access when copying [duplicate]

I am having a difficult time how to properly copy specific field data from previous records on my user form. I don't have a code sample to show but my request is very simplistic.
Currently, out of 12 fields, I have 6 that I often repeat data. I can click on and press Ctrl+' ("Insert the value from the same field in the previous record") and it performs the task I want. However, it adds a lot of time to the task. I simply want to write VBA code to perform that command to those specific fields.
I haven't been able to get SendKeys to work. DLast appears to provide random data at times. I feel like this should be a very simple request but for some reason I am not finding a functional solution for it.
Don't fiddle with arrays or queries - use the power of DAO:
Private Sub CopyButton_Click()
CopyRecord
End Sub
If a record is selected, copy this.
If a new record is selected, copy the last (previous) record.
Private Sub CopyRecord()
Dim Source As DAO.Recordset
Dim Insert As DAO.Recordset
Dim Field As DAO.Field
' Live recordset.
Set Insert = Me.RecordsetClone
' Source recordset.
Set Source = Insert.Clone
If Me.NewRecord Then
' Copy the last record.
Source.MoveLast
Else
' Copy the current record.
Source.Bookmark = Me.Bookmark
End If
Insert.AddNew
For Each Field In Source.Fields
With Field
If .Attributes And dbAutoIncrField Then
' Skip Autonumber or GUID field.
Else
Select Case .Name
' List names of fields to copy.
Case "FirstField", "AnotherField", "YetAField" ' etc.
' Copy field content.
Insert.Fields(.Name).Value = Source.Fields(.Name).Value
End Select
End If
End With
Next
Insert.Update
Insert.Close
Source.Close
End Sub
This also, by the way, is an excellent example of the difference between the RecordsetClone and the Clone of a recordset - the first being "the records of the form", while the second is an independant copy.
This also means, that the form will update automatically and immediately.
Provided that it's a simple form to edit a simple table, and that the bound data field names match the control names, you may get away with
If Me.Recordset.AbsolutePosition > 0 Then
With Me.Recordset.Clone()
.AbsolutePosition = Me.Recordset.AbsolutePosition - 1
Dim control_name As Variant
For Each control_name In Array("field1", "field2", "field3", "field4", "field5", "field6")
Me.Controls(control_name).Value = .Fields(control_name).Value
Next
End With
End If
which you assign to a separate button on the same form.
You have a good idea post here already.
You could also say place a function in the before insert event. This event ONLY fires when you start typing into a NEW reocrd, and it becomes dirty.
So, maybe this:
Private Sub Form_BeforeInsert(Cancel As Integer)
Dim rstPrevious As DAO.Recordset
Dim strSQL As String
strSQL = "SELECT TOP 1 * FROM tblPeople ORDER BY ID DESC"
Set rstPrevious = CurrentDb.OpenRecordset(strSQL)
' auto file out some previous values
If rstPrevious.RecordCount > 0 Then
Me.Firstname = rstPrevious!Firstname
Me.LastName = rstPrevious!LastName
End If
End Sub
And some good ideas in say having a "list" or "array" of controls/fields to setup, so you don't have to write a lot of code. (as suggested in the other post/answer here)

Generate Records to Add to Table - Loop or Recordset? [duplicate]

Where I work we receive electronic meters from customers and try to solve the errors they have. We will receive 4-8 meters at a time that all have the same problem, same specs, same everything, the only thing different between each meter is the Serial Number. I want to be able to enter every serial number, and the common specs all in one form to create multiple records.
Here's a pic of what I have for the form. I was able to create records for just one serial number at a time, but I would like to do it all at once to make data entry quicker and easier.
Meter Entry Form
So summary, Multiple Meters, all identical specs, different serial numbers. I want to enter it all into a form and have multiple records created. Thanks for any help or insight you can provide me.
-Chris
You could bind a subform to the table that stores your meter records and then have some unbound fields on your main form that allows you to enter the information that would be repeated in your batch of records. You could also put another unbound text box on the main form to specify the number of records you want that will have this repeated information.
So in the mock-up below, you'd specify how many records you want (red box), e.g. 10 records:
Then you'd supply the data that would be repeated for these 10 records (blue boxes):
You'd then click a button that would create the number of records specified with the repeated information given:
It would then just be a case completing the unique serial number for each of the records in the batch you have generated.
Here's the VBA I used on the Add button:
Private Sub cmdAddRecords_Click()
batchAdd Me.txtRecords
Me.tblMeters_sub.Requery
End Sub
...and the batchAdd sub routine it calls:
Public Sub batchAdd(records As Integer)
Dim db As DAO.Database
Dim rs As DAO.Recordset
Dim i As Integer
Set db = CurrentDb
Set rs = db.OpenRecordset("tblMeters")
i = 1
Do While i <= records
rs.AddNew
rs!SerialNumber = ""
rs!MeterFirmware = Me.MeterFirmware
rs!MeterCatalog = Me.MeterCatalog
rs!Customer = Me.Customer
rs!MeterKh = Me.MeterKh
rs!MeterForm = Me.MeterForm
rs!MeterType = Me.MeterType
rs!MeterVoltage = Me.MeterVoltage
rs.Update
i = i + 1
Loop
rs.Close
Set rs = Nothing
Set db = Nothing
End Sub
Here's a link to the mock-up (if you want a closer look).
Update
In response to your query about whether the subform could be filtered so it doesn't just become a big list of all meters, you could add another field to the tblMeters table that will take the date and time that you added records to the table:
You'd then need to add another line to the batchAdd sub that will put the system time and date in this new field:
...
Do While i <= records
rs.AddNew
rs!SerialNumber = ""
rs!MeterFirmware = Me.MeterFirmware
rs!MeterCatalog = Me.MeterCatalog
rs!Customer = Me.Customer
rs!MeterKh = Me.MeterKh
rs!MeterForm = Me.MeterForm
rs!MeterType = Me.MeterType
rs!MeterVoltage = Me.MeterVoltage
rs!DateAdded = Now ' <-- HERE!
rs.Update
i = i + 1
Loop
...
You'll then need to change the subform's Record Source property (Design View > select subform > Property Sheet > Data tab > Record Source):
Put the following SQL in there:
SELECT TOP 15 tblMeters.SerialNumber, tblMeters.MeterFirmware, tblMeters.MeterCatalog,
tblMeters.Customer, tblMeters.MeterType, tblMeters.MeterForm, tblMeters.MeterKh,
tblMeters.MeterVoltage, tblMeters.DateAdded
FROM tblMeters
ORDER BY tblMeters.DateAdded DESC;
... which will order the records by the date/time field (most recent at the top) and then show only the first 15 of these records. If you want a different number of records change the TOP 15 bit to a different number of your choosing.
When you click "Add", your new batch of records should be added to the top of the list and the list should stay at a maximum of 15 records (or whatever number you specify in TOP ...)
Be aware that when I was testing this, clicking the "Add" button rapidly a few times seemed to cause the sql to not bother with the TOP ... filter, but as long there's like a second or more between each "Add" click it seemed to work fine.
Hope this helps.

vba store recordset as integer variable

First time poster, I finally had a question that I couldn't find an answer to here.
I have an MS Access query that returns 1 result (which is a number) that I want to store as an integer variable (x) so I can use it later for a loop. The issue is that because I'm using it as a recordset and the variable is an integer, I'm receiving a "Type Mismatch" error.
Right now I'm just storing the result to a cell and setting the variable equal to the cell:
Ws.Range("A1") = Db.OpenRecordset("SELECT COUNT(Asset_Name) FROM Assets WHERE Active = True").GetRows(1)
x = Ws.Range("A1")
Ws.Range("A1").Delete
And then later I just have a loop that runs x times:
For i = 0 To x
Basically, I just want to have some code that looks like this:
x = Db.OpenRecordset("SELECT COUNT(Asset_Name) FROM Assets WHERE Active = True").GetRows(1)
Any help here would be huge. Thank you!
The following should give you the correct result:
Dim x As Integer
Dim db As DAO.Recordset
db.MoveFirst
If IsNumeric(db.OpenRecordset("SELECT COUNT(Asset_Name) FROM Assets WHERE Active = True").Fields(0).Value) Then
x = CInt(db.OpenRecordset("SELECT COUNT(Asset_Name) FROM Assets WHERE Active = True").Fields(0).Value)
Else
MsgBox "The query did not return a number." & Chr(10) & "Aborting..."
End If
Note, that you are using DAO and not ADO as your original tags on the post indicated. Still, they both behave rather similar and the cursor is normally on the first row (when the data is returned). So, MoveFirst should not be necessary. Still, Microsoft themselves keep using it in its own sample code all the time. The first column if for DAO and ADO alike .Fields(0).

VBA - Looping through filtered table in access

Access 2013 32 Bit / Windows 7 64 Bit
I have a table of keys and based on the key value my vba will run some queries and populate other fields in the table - I call this "Checking" I have a "Checked" Column in the table and have to break the processing of this list into several batches (and more records are constantly added) so I'd like to filter out the "Checked" ones. I'd like to do this WITHOUT using a separate query
I'm using the traditional loop w/ a condition:
(My code works this is just a mock up ignore syntax here please)
Move First
Do Until EOF
if Table("Checked") = "True" Then goto NextRow
<Code>
NextRow:
Move Next
Loop
I'd like to continue with this method, but filter out all of the "Checked" = True on the onset
Simply open your recordset with a query that has a WHERE clause.
Dim rs As Recordset
Dim S As String
S = "SELECT foo, morefoo FROM bar WHERE [Checked] = 0"
' Or if Checked is a Text column:
S = "SELECT foo, morefoo FROM bar WHERE [Checked] <> 'True'"
Set rs = CurrentDb.OpenRecordset(S)
Do While Not rs.EOF
' code
rs.MoveNext
Loop
(BTW, your Move First inside the loop would create an endless loop...)
I ended up sorting the field then exiting the sub when I reached a row marked as checked.

Populating reports with calculated values

I hope this is a simple question and you don't have to waste too much of you time on it.
I have an report (called repRAD78) which contains a textbox (called txtRAD8). I would like to populate txtRAD8 with a calculated value based on numbers pulled from a query called qryrRAD78.
Looking through the forums it looks like recordsets would be the solution but this is my first foray into recordsets and it's not going well. :(
The code I have pasted in below I have pulled together from a number of places and it doesn't produce any errors but puts the same value into txtRAD8 for all the records.
I'm sorry if this is a stupid question but it's been driving me potty.
Many thanks for your time.
Al.
Public Sub Calc()
Dim dbs As DAO.Database
Dim rst As DAO.Recordset
Set dbs = CurrentDb
Set rst = dbs.OpenRecordset("qryrRAD78")
rst.MoveFirst
Do Until rst.EOF = True
Dim lngMean As Long
Dim lngRAD78max As Long
Dim lngRAD78_1 As Long
Dim lngRAD78_2 As Long
Dim lngRAD78_3 As Long
Dim lngRAD7 As Long
Dim lngRAD8 As Long
lngRAD78_1 = rst![RAD78_1]
lngRAD78_2 = rst![RAD78_2]
lngRAD78_3 = rst![RAD78_3]
lngRAD8b_c = rst![RAD8b_c]
lngMean = (lngRAD78_1 + lngRAD78_2 + lngRAD78_3) / 3
lngRAD78max = Maximum(Abs(lngRAD78_1), Abs(lngRAD78_2), Abs(lngRAD78_3))
lngRAD7 = ((lngRAD78max - lngMean) / lngMean) * 100
lngRAD8 = ((lngMean - lngRAD8b_c) / lngRAD8b_c) * 100
txtRAD8.Value = lngRAD8
rst.MoveNext
Loop
rst.Close
dbs.Close
End Sub
Private Sub Detail_Format(Cancel As Integer, FormatCount As Integer)
Calc
End Sub
Here's a second approach to this. Rather than using a function in the code, take the calculations from your Calc() routine and put them in another query.
SELECT idrRAD78,
(RAD78_1 + RAD78_2 + RAD78_3) AS Mean,
(IIf(Abs(RAD78_1) > Abs(RAD78_2),
IIf(Abs(RAD78_1) > Abs(RAD78_3), RAD78_1, RAD78_3),
IIf(Abs(RAD78_2) > Abs(RAD78_3), RAD78_2, RAD78_3))) AS RAD78Max,
(((RAD78max - Mean) / Mean) * 100) AS RAD7,
(((Mean - RAD8b_c) / RAD8b_c) * 100) AS RAD8
FROM qryrRAD78
This will give you a query that performs the same calculations as your existing function. Then just edit the report query to join to this new query (just like joining a table) using something like:
FROM ReportQuery INNER JOIN NewQuery ON ReportQuery.idrRAD78 = NewQuery.idrRAD78
Change the query names to match the real names. Add the fields from the new query in the SELECT part of your report query:
SELECT <existing field list>, RAD7, RAD8
Then set txtRAD8 to the RAD8 field.
I'm just doing this from memory as I'm not in front of my own computer, but hopefully that makes sense and is close enough to the correct code.
The problem with this function is that every row on the report is going to have a textbox called txtRAD8. So what you are really doing is updating every textbox on the report with the same value (once for every loop through the recordset). You are not actually setting the value for each individual row.
What you need to do is make the value of the textbox = Calc(RowID). Then your query uses the passed-in parameter to get the value for that one record instead of looping through the whole recordset, and updates just that one row on the report.
So your Sub becomes a Function, and returns the calculated value.