Question

DCount too slow

Asked by: verdante

Hi
I'm in  tearing hurry (thus the points). I have a number of textboxes that count where certain conditions are true. Thery are all located in a form which is bound to a query called Diabetes_Master which contains all the fields I need to query. As a novice I jumped to the first thing that worked which is DCount but it takes far too long. Can someone tell me what I can put in the Control Source of the fields to speed up performance. An example of one field is included below:

=DCount("*","Diabetes_Master","([Total_C]<4.0)")

cheers
Verdy

This Question has been solved and asker verified All Experts Exchange premium technology solutions are available to subscription members.

Subscribe now for full access to Experts Exchange and get

Instant Access to this Solution

  • Plus...
  • 30 Day FREE access, no risk, no obligation
  • Collaborate with the world's top tech experts
  • Unlimited access to our exclusive solution database
  • Never be left without tech help again

Subscribe Now

Asked On
2005-12-01 at 16:11:01ID21650189
Tags

dcount

,

too

Topic

Microsoft Access Database

Participating Experts
5
Points
500
Comments
20

Trusted by hundreds of thousands everyday for fast, accurate and reliable tech support.

  • "The time we save is the biggest benefit of Experts Exchange to Warner Bros. What could take multiple guys 2 hours or more each to find is accessed in around 15 minutes on Experts Exchange." Mike Kapnisakis, Warner Bros.
  • "Our team likes having a resource that is more secure than just using Google and most experts using this service really know their stuff. It's nice to look here first versus using Google." Dayna Sellner, Lockheed Martin
  • "Anytime that I've been stumped with a problem, 9 out of 10 times Experts Exchange has either the accepted solution or an open discussion of the potential solution to the problem." Kenny Red, eBay Inc.

See what Experts Exchange can do for you.

Got a question?

We've got the answer.

Experts Exchange has been collecting answers to technology questions since 1996…3 million and counting! If you have a question, chances are we already have your answer.

Screenshot of Experts Exchange Knowledgebase

Need individual assistance?

Our experts are ready to help.

If you can't find the exact answer you're looking for, ask our exclusive community of 50,000 experts. You’ll get a personalized answer from a trusted professional.

Screenshot of Experts Exchange Knowledgebase

Want to learn from the best?

Read articles from industry experts.

Thousands of free tech tips, tricks, how-to’s and tutorials are available in our peer reviewed articles section. See for yourself how smart our experts are, no login required.

Screenshot of an Article

Working on a long term project?

Store your work and research.

Save solutions to your questions, answers you’ve discovered through searching plus helpful articles in your personal knowledgebase for easy future access.

Screenshot of Experts Exchange Knowledgebase

Access the answers to your technology questions today.

Subscribe Now

30-day free trial. Register in 60 seconds.

What Makes Experts Exchange Unique?

Members of the expert community talk about why the experience at Experts Exchange is different than what you will find anywhere else.

Trusted by the world's most respected brands.

image of each brand's logo

Faithfully serving IT professionals since 1996.

Experts Exchange Logo

Try it out and discover for yourself.

Subscribe Now

30-day free trial. Register in 60 seconds.

Related Solutions

    Free Tech Articles

    1. WARNING: 5 Reasons why you should NEVER fix a computer for free.
      It is in our nature to love the puzzle. We are obsessed. The lot of us. We love puzzles. We love the challenge. We thrive on finding the answer. We hate disarray. It bothers us deep in our soul. W...
    2. SCCM OSD Basic troubleshooting
      SCCM 2007 OSD is a fantastic way to deploy operating systems, however, like most things SCCM issues can sometimes be difficult to resolve due to the sheer volume of logs to sift through and the dispe...
    3. Migrate Small Business Server 2003 to Exchange 2010 and Windows 2008 R2
      This guide is intended to provide step by step instructions on how to migrate from Small Business Server 2003 to Windows 2008 R2 with Exchange 2010. For this migration to work you will need the fo...
    4. Create a Win7 Gadget
      This article shows you how to create a simple "Gadget" -- a sort of mini-application supported by Windows 7 and Vista. Gadgets can be dropped anywhere on the desktop to provide instant information, ...
    5. Outlook continually prompting for username and password
      There have been a lot of questions recently regarding Outlook prompting for a username and password whilst using Exchange 2007. There are a few reasons why this would happen and I will try to cover t...
    6. Backup Exchange 2010 Information Store using Windows Backup
      There seems to be quite a lot of confusion around the ability to backup Exchange 2010 using the built in Windows Backup feature. This stems from the omission of this feature prior to Exchange 2007 s...

    Cloud Class Webinars

    1. Avoiding Bugs in Microsoft Access
      Alison Balter takes and in-depth look at avoiding bugs in Access. In this webinar you will learn about using the immediate window to debug your applications, invoking the debugger, using breakpoints to troubleshoot, stepping through code, setting the next statement to execute, ...
    2. Top 10 Best New Features in Visio 2010
      Scott Helmers gives live demonstrations of the top 10 new features in Visio 2010. This webinar will teach you how to create compelling diagrams by adding shapes to the page with a single click, linking the shapes in a diagram to data in Excel (or SQL Server, or SharePoint), ...
    3. IT Consultant Business Secrets Revealed
      Michael Munger, Experts Exchange tech pro and IT consultant, pulls back the curtain on his very successful businesses and answers question on every IT consultant and business owner should know about. He shares secrets on what he did to solve the 5 most common problems in IT, ...
    4. Disaster Recovery and Business Continuity
      Quest CTO, Mike Billon, gives an overview of the steps involved in building a dunamic disaster recovery plan. Through case studies and an examination of software/hardware tooles for monitoring and testing, you'll gain a better understandin of where you are, where you want ...
    5. Organize Your Visio Diagrams with Containers and Lists
      Scott Helmers uses cross functional flowcharts, wireframe diagrams, data graphic legends and seating charts to teach you: how to ustilize all three new structured diagram components in Visio 2010, the best practices for organizeing shapes in previous version of Visio, how to organize ...
    6. How to Us Objects, Properties, Events and Methods in Microsoft Access
      Alison Dalter gives an in-depbth look at objects, properties, events and methods in Microsoft Access. In this webinar you will learn about using the object browser, referring to objects, working with properties and methods, working with object variables, understanding the ...

    Join the Community

    Give a Little. Get a Lot.

    Join the community of experts here and help other tech pros by answering question in your area of expertise. You can earn FREE access to all Experts Exchange's premium features and resources.

    Join the Community

    Answers

     

    by: mgrattanPosted on 2005-12-01 at 16:27:50ID: 15401566

    Here's a custom function that takes the same parameters and is much faster since it uses recordsets.

    Function tCount(pstrField As String, pstrTable As String, pstrCriteria As String) As Long
        On Error GoTo tCount_Err
        ' Function tCount
        ' Purpose: Replace DCount, which is slow on attached tables
       
        Dim dbCurrent As DAO.Database
        Dim rstLookup As DAO.Recordset
        Dim lngCount As Long
       
        Set dbCurrent = DBEngine(0)(0)
        If pstrCriteria = "" Then
            If pstrField = "*" Or pstrField = "" Then
                Set rstLookup = dbCurrent.OpenRecordset("Select Count(*) From " & pstrTable, dbOpenSnapshot)
            Else
                Set rstLookup = dbCurrent.OpenRecordset("Select Count(" & pstrField & ") From " & pstrTable, dbOpenSnapshot)
            End If
        Else
            If pstrField = "*" Or pstrField = "" Then
                Set rstLookup = dbCurrent.OpenRecordset("Select Count(*) From " & pstrTable & " Where " & pstrCriteria, dbOpenSnapshot)
            Else
                Set rstLookup = dbCurrent.OpenRecordset("Select Count(" & pstrField & ") From " & pstrTable & " Where " & pstrCriteria, dbOpenSnapshot)
            End If
        End If
        If Not rstLookup.BOF Then
            rstLookup.MoveFirst
            lngCount = rstLookup(0)
        Else
            lngCount = 0
        End If
        rstLookup.Close
        tCount = lngCount
       
       
       
    tCount_Exit:
        On Error Resume Next
        rstLookup.Close
        Exit Function
       
    tCount_Err:
        Select Case Err
            Case Else
        End Select
       
        ' Retry/Abort/Ignore
       
        Select Case MsgBox(Error, MB_ABORTRETRYIGNORE Or MB_ICONEXCLAMATION, "Error " & Err)
            Case IDABORT
                Resume tCount_Exit
            Case IDRETRY
                Resume
            Case IDIGNORE
                Resume Next
        End Select
        Exit Function
    End Function

     

    by: netcoolPosted on 2005-12-01 at 16:56:02ID: 15401698

    I have a suggestion, you can place all Your DCount function in the Form_Load Event.

    Remove from the text box ControlSource and try in Form_Load Event.

    just try

     

    by: netcoolPosted on 2005-12-01 at 16:57:35ID: 15401705

    like this

    Private Sub Form_Load()
    Text4 = DCount("*", "Table1", "( [Table1]![Data]< 10)")
    End Sub

     

    by: ArjiPosted on 2005-12-01 at 17:10:58ID: 15401763

    Not sure if this will help. You can place this in a public module and then call it like DCount. It may not speed things up but then again I've always found it to be quite fast. You can tailor it to filter the the parameters but generally just follow the DCount rules.  Hope it helps.

    Use:
    MyDCount("*", "Diabetes_Master", "Total_C<4.0")

    '***************************
    Public Function MyDCount(MyField As String, MyTable As String, MyCriteria As String) as long

    Dim MyDataBase As Database, MyTable As Recordset
    Dim strSQL As String

    strSQL = "Select " & MyField & " from " & MyTable & " WHERE ” & MyCriteria

    Set MyDataBase = CurrentDb()
    Set MyTable = MyDataBase.OpenRecordset("strSQL")          ' Open Recordset.
    MyTable.MoveLast

    MyDCount = MyTable.RecordCount

    MyTable.Close
    Set MyTable = Nothing
    MyDataBase.Close
    set mydatabase = nothing

    End Function

     

    by: dannywarehamPosted on 2005-12-02 at 03:10:34ID: 15403704

     

    by: eddiejPosted on 2005-12-02 at 06:44:29ID: 15404876

    Do some or all of the text box counts come from the same table? You may be able to combine a few of the above answers to speed things up even more.

    for example if you have 5 text boxes to fill with counts from different fields in the same table.  Leave the text boxes unbound, open a recordset with the 5 fields and every record. Loop thru the recordset, filling the 5 variables with the count, put the counts in the text boxes at the end.

    You would only open one recordset, and only loop thru it once.
    eddiej

     

    by: ArjiPosted on 2005-12-02 at 09:00:56ID: 15406122

    Oops! I found a small error in my function.  I created a duplicate definition with 'MyTable as String'. Should Be:

    Public Function MyDCount(MyField As String, MySearchTable As String, MyCriteria As String) as long
    Dim MyDataBase As Database, MyTable As Recordset
    Dim strSQL As String

    strSQL = "Select " & MyField & " from " & MySearchTable & " WHERE ” & MyCriteria

    Set MyDataBase = CurrentDb()
    Set MyTable = MyDataBase.OpenRecordset("strSQL")          ' Open Recordset.
    MyTable.MoveLast

    MyDCount = MyTable.RecordCount

    MyTable.Close
    Set MyTable = Nothing
    MyDataBase.Close
    set mydatabase = nothing

    End Function

     

    by: ArjiPosted on 2005-12-02 at 09:19:33ID: 15406267

    I also found something very weird while testing the function.  You can't use an upper case 'WHERE' when concactenating the strSQL statement.  Also, the function is very fast:

    Change this:0
    strSQL = "Select " & MyField & " from " & MySearchTable & " WHERE ” & MyCriteria

    To this:
    strSQL = "Select " & MyField & " from " & MySearchTable & " where ” & MyCriteria

    It's weird but Access keeps appending a (") at the of the first statement where 'Where' is uppercase. Very strange.


    ************************************
    Get a count of Customer that start with the letter C:

    MyDCount("*", "tblCustomers", "fldConsignee Like '*C*'")
    **********************************************

    Get a count of Customer named Joe Blo:

    MyDCount("*", "tblCustomers", "fldConsignee='Joe Blo'")
    **********************************************

     

    by: ArjiPosted on 2005-12-02 at 09:26:17ID: 15406332

    Here's another improvement. Make the MyCriteria Optional so it behaves more like DCount.  Leaving out the criteria will count all records in the recordset.

    Get a count of all records in Diabetes_Master:

    =MyDCount("*","Diabetes_Master")

    **********************************************
    Public Function MyDCount(MyField As String, MySearchTable As String, Optional MyCriteria As String) As Long

    Dim MyDataBase As Database, MyTable As Recordset
    Dim strSQL As String

    If IsNull(MyCriteria) Then
        strSQL = "Select " & MyField & " from " & MySearchTable & " where " & MyCriteria
    Else
        strSQL = "Select " & MyField & " from " & MySearchTable
    End If

    Set MyDataBase = CurrentDb()
    Set MyTable = MyDataBase.OpenRecordset(strSQL)          ' Open Recordset.
    MyTable.MoveLast

    MyDCount = MyTable.RecordCount

    MyTable.Close
    Set MyTable = Nothing
    MyDataBase.Close
    Set MyDataBase = Nothing

    End Function

     

    by: ArjiPosted on 2005-12-02 at 09:35:56ID: 15406419

    Dang, I'm pretty sloppy today.  Here's another correction:

    If Not IsNull(MyCriteria) Then
        strSQL = "Select " & MyField & " from " & MySearchTable & " where " & MyCriteria
    Else
        strSQL = "Select " & MyField & " from " & MySearchTable
    End If

     

    by: mgrattanPosted on 2005-12-02 at 09:41:24ID: 15406460

    Arji,

    What's the difference between the function you posted and the original one that I posted?  Seems like the same basic idea of using recordsets and dynamic SQL to retrive the result.

    Mike

     

    by: ArjiPosted on 2005-12-02 at 14:09:10ID: 15408491

    Just less processing to keep it as fast as possible. Your Set rstLookup = .... statements will slow things down.  Instead of using a Count field and then reading the results, I simply read a property of the recordset(RecordCount). It's much faster because there is no field processing(Count).  I just open the recordset and grab the recordcount.  DCount is still probably faster but it's always worth a try. It also depends on whether the criteria field is indexed or not. That is probably the only way to speed things up significantly.

     

    by: mgrattanPosted on 2005-12-02 at 14:15:14ID: 15408540

    Aha...I posted the wrong function!  I meant to post a different function that uses the same methodology as yours Arji.  Looks like I need to update my source code library.

     

    by: ArjiPosted on 2005-12-02 at 14:18:36ID: 15408562

    Yeah, I always try to use properties of recordsets if I can. RecordCount is a valuable one.

     

    by: mgrattanPosted on 2005-12-02 at 14:24:35ID: 15408607

    One tip for your function though.  Before using the MoveLast method, you should check to make sure the recordset isn't empty.

    If Not MyTable.BOF and Not MyTable.EOF Then
       MyTable.MoveLast
       MyDCount = MyTable.RecordCount
    Else
       MyDCount = 0
    End If

     

    by: ArjiPosted on 2005-12-02 at 15:30:55ID: 15409053

    Actually if it was empty then RecordCount would be 0. In Access 2003 you really don't have to jump the end to get an accurate count.  I think there is a problem with early versions though. So this would be good too:

    if MyTable.RecordCount > 0 then
       MyDCount = MyTable.RecordCount
    Else
       MyDCount = 0
    end if

     

    by: mgrattanPosted on 2005-12-02 at 15:37:52ID: 15409096

    I'm in the habit of checking BOF and EOF from earlier versions.  Trying to go to the last record using MoveLast would generate an error if there were no records.  That's been fixed in 2003?  Good to know.

     

    by: ArjiPosted on 2005-12-04 at 18:11:28ID: 15416879

    verdante,
    Thanks for the points.  Did it work any faster than DCount for your situation?

     

    by: verdantePosted on 2005-12-04 at 19:08:31ID: 15417110

    Arji
    Sure did! Was looking at a database with 10K records. Thanks a heap,
    Verdy

     

    by: ArjiPosted on 2005-12-04 at 21:16:28ID: 15417457

    Cool!  Sometimes and external function can be slower than an internal function. There are so many situations where it's faster in one way than it is with another.  Glad it worked for you.

    20120131-EE-VQP-002

    3 Ways to Join

    30-Day Free Trial

    The Experts

    98% positive feedback on 31,087 answers since March 2000. angeliii is a Microsoft Most Valuable Professional for his work with MS SQL Server & Develoment.

    He has also proven his knowledge of Visual Basic Programming, PHP Scripting and Oracle Databases.

    The Experts

    97% positive feedback on 10,752 answers since July 2000. lrmoore has more than 18 years experience in the networking industry.

    The six-time Mircosoft MVPs specialties include firewalls, virtual private networking, and network management.

    Testimonials

    "...and excellent source for support... Kind of like having your very own IT dept." Electriciansnet

    Testimonials

    "I was apprehensive at signing up at first. However... it has already made my life as an IT administrator much easier." JaCrews

    Testimonials

    "WOW! You guys have great, active, and knowledgeable people on here." moore50

    Business Clients

    Business Clients

    In the Press

    "If you’ve got a question... Experts Exchange can supply an answer.”

    In the Press

    "...an invaluable aid for both IT professionals and those who require tech support."

    In the Press

    "where IT professionals provide quick answers on just about any topic"

    Business Account Plans

    Loading Advertisement...