Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Record count in Access table using VBA

Tags:

vba

ms-access

I'm trying to get the record count of a table, and if count is greater than 17, create a new table.

Dim rst As DAO.Recordset
strSQL = "Select * from SKUS"
Set rst = db.OpenRecordset(strSQL)

If rst.RecordCount > 17 Then
    Set tdf = db.CreateTableDef("161-0363")

    Set fld = tdf.CreateField("SKUS", dbText, 30)
    tdf.Fields.Append fld

    Set fld = tdf.CreateField("Count", dbInteger)
    tdf.Fields.Append fld

    db.TableDefs.Append tdf
End If

This code doesn't create a new table, but when I change the if statement to this, it works:

...
If rst.RecordCount > 0 Then
    Set tdf = db.CreateTableDef("161-0363")
...

So the RecordCount is returning 1, I think. Why is this happening? I know for sure the table has 18 rows in it.
Can anyone help me out?

like image 655
Shubham Avatar asked Jul 20 '11 17:07

Shubham


People also ask

How do I count records in Access VBA?

You can use the DCount function to determine the number of records that are in a specified set of records (a domain). Use the DCount function in a Visual Basic for Applications (VBA) module, a macro, a query expression, or a calculated control.

How do I count records in Access table?

On the Home tab, in the Records group, click Totals. A new Total row appears below the last row of data in your datasheet. In the Total row, click the field that you want to sum, and then select Count from the list.


1 Answers

You have to force the recordset to move through all the rows to get an accurate count. Try this:

...
Set rst = db.OpenRecordset(strSQL)

rst.MoveLast
rst.MoveFirst
If rst.RecordCount > 17 Then
...

Unless you are doing something else with the recordset that you're not showing in your snippet, you can simplify your code by just doing a check of the record count using the domain count function:

If DCount("*", "SKUS") > 17 Then
like image 65
mwolfe02 Avatar answered Sep 23 '22 13:09

mwolfe02