Question

VBA ADO recordset returning one less record than actual query

Asked by: DallasDAF

I'm currently utilizing a function that creates a worksheet, and then pulls data from an access database query to populate the new worksheet.  In particular, I'm querying an Access query based on a date field.  I'm expecting 3 records, which is what I get when I print the sql and paste in an Access query.  I'm only receiving the first 2 records, however.  What is odd is that if I break in the middle of the code, and then resume, I will often get the proper number of records (3).  I'm wondering how I can consistently ensure that I'm pulling an accurate recordset.  Any ideas?

Function createDetailWorksheet(dbName As String)
'create the detailed worksheet
 
' connect to the Access database
cn.Open "Provider=Microsoft.Jet.OLEDB.4.0; Data Source= " & dbName & ";"
If cn.State <> adStateOpen Then Exit Function
 
 
'Set the date
strDate = rngDates.Value
 
'Add the new worksheet, name it, and set the range where field headers will go
Sheets.Add After:=Sheets(Worksheets.Count), Count:=1, Type:=xlWorksheet
Set wsDetailData = ActiveSheet
'Add function here to convert to correct date format
wsDetailData.Name = "Detail_" & Mid(strDate, 1, 1) & Mid(strDate, 3, 2) & Mid(strDate, 6, 4)
Set rngData = Worksheets(wsDetailData.Name).Range("C4")
 
'Set the query
strSql = "Select " & strDetailFields & " from qryTradeData where [date]=#" & strDate & "#"
    
' open the recordset
With rs
 
' open the recordset
.Open strSql, cn, adOpenStatic 'adLockOptimistic, adCmdText
.MoveLast
 
    
If .RecordCount > 0 Then
    .MoveFirst
Do While Not .EOF
    'print data here
 
Loop
End If
End With
 
rs.Close
Set rs = Nothing
cn.Close
Set cn = Nothing
End Function

                                  
1:
2:
3:
4:
5:
6:
7:
8:
9:
10:
11:
12:
13:
14:
15:
16:
17:
18:
19:
20:
21:
22:
23:
24:
25:
26:
27:
28:
29:
30:
31:
32:
33:
34:
35:
36:
37:
38:
39:
40:
41:
42:
43:

Select allOpen in new window

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
2009-08-16 at 15:13:18ID24656851
Tags

Excel Access VBA ADO recordset

Topics

Microsoft Access Database

,

SQL Query Syntax

,

Microsoft Excel Spreadsheet Software

Participating Experts
3
Points
500
Comments
23

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

  1. Crystal Reports with ADO recordsets.
    Hi, I'm working with VB6 and Crystal Reports 8. Basically, I'm using a reference to the CRAXDRT library. All I want to do is to set a Crystal Report object, and somehow pass it an ADO recordset, so it can populate itself. Is this possible?! I've seived through the documen...
  2. Saving to a File from ADO RECORDSET
    I need to save the details of a recordset directly into a .xls file(Excel File).Is there any method in ADO Recordset which supports this. I would appreciate an immediate answer.
  3. Excel using VBA - Convert Worksheet to Recordset
    Is there a way I can convert a worksheet to a recordset object? How?
  4. Access unbound form, bind to ADO recordset
    Can someone provide an example of this. I have an ADO recordset populated with data from Sql. I want to assign the values to the fields and have some sort of record selector. I do not want to use built in access binding.
  5. Creating Excel File from iterating ado recordset
    A query populates the ado recordset that I have in my application. That query may execute number of times with different values as the where clause and each time a new recordset is generated with exactly same attributes. The result is dynamic and may contain recordcount from ...

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: thenelsonPosted on 2009-08-16 at 15:43:10ID: 25110750

Try changing
Do While Not .EOF
To
Do Until .EOF
(Probably not the problem.)

What is between?
Do While Not .EOF

Loop

 

by: thenelsonPosted on 2009-08-16 at 15:44:52ID: 25110753

This might fix it:
Do

Loop Until .EOF

 

by: acperkinsPosted on 2009-08-16 at 18:14:20ID: 25111172

Do it this way:

' open the recordset
With rs
 
      ' open the recordset
      .Open strSql, cn, adOpenStatic 'adLockOptimistic, adCmdText
      '                        .MoveLast
 
   
      '                        If .RecordCount > 0 Then
      '                              .MoveFirst
      Do While Not .EOF
          'print data here
 
      Loop
      '                        End If
End With

 

by: acperkinsPosted on 2009-08-16 at 18:15:39ID: 25111175

With rs
      ' open the recordset
      .Open strSql, cn, adOpenStatic 'adLockOptimistic, adCmdText
      Do While Not .EOF
          'print data here
 
      Loop
End With

 

by: DallasDAFPosted on 2009-08-16 at 20:29:34ID: 25111500

acperkins,

I'm not sure what was different in what you did.  Either way, neither way has fixed this issue.  Any other ideas?

 

by: DallasDAFPosted on 2009-08-16 at 20:41:21ID: 25111524

To give you an idea, it's not really the looping that is incorrect.  Like I said, if I break in the middle, or rahter, if I put a break point, and run it, it will show the correct record count of 3.  If I let it just run through, it will only show 2.  I think it has something to do with it not having enough time to catch all 3 records upon opening the recordset, but it's very strange.  Other thoughts?

 

by: thenelsonPosted on 2009-08-16 at 20:57:20ID: 25111554

How about using for next instead of do loop?
Dim i As Integer
For i = 1 To .RecordCount

Next i

 

by: DallasDAFPosted on 2009-08-16 at 21:00:26ID: 25111559

thenelson,
The problem with that is .recordcount would equal 2 so it would be incorrect.  What's the safest way to load a recordset if I have the query?  This obviously has problems associated with it.

 

by: LSMConsultingPosted on 2009-08-17 at 03:14:57ID: 25112844

As others have indicated, .RecordCount with ADO Recordsets aren't guaranteed to be accurate. Using Do loops, or some other method that checks for EOF, is the correct way to do that.

Could it be that you're comparing dates incorrectly? Access stores the time with your dates (unless you specifically format that date BEFORE it's stored in the table), so
sometimes comparing

MyDateField = SomeDateValue

won't work IF you have value like this:

MyDAteField = 01/01/2009 12:13:33
SomeDateValue = 01/01/2009

You can try Format:

SELECT * FROM SomeTable WHERE Format("mm/dd/yyyy", MyDateField) = #01/01/2009#

 

by: DallasDAFPosted on 2009-08-17 at 04:53:35ID: 25113360

LSM,

This is a good thought, but still isn't getting to the core issue (works when I break, but not other times).  As a workaround, I entered:

msgbox "Loading Trades"

directly after I assign strSql.  This seems to work, however, I'd like to determine how to ensure that I always load the correct number of records.  Other thoughts?

 

by: thenelsonPosted on 2009-08-17 at 05:42:52ID: 25113694

Is strDate a string and rngDates a date? So you are converting a date to a string then converting it look to a dote again in strSQL.  Try this:

strSql = "Select " & strDetailFields & " from qryTradeData where [date]=#" & rngDates & "#"

 

by: thenelsonPosted on 2009-08-17 at 05:50:01ID: 25113773

Is rngDates coming from a spreadsheet?  If so, then perhaps there is a timing issue.   Try placing a DoEvents before the .Open strSql line:

DoEvents
.Open strSql, cn, adOpenStatic 'adLockOptimistic, adCmdText

 

by: DallasDAFPosted on 2009-08-17 at 06:58:37ID: 25114483

Tried both, same issue.  Again, the only thing that seems to work is inserting a msgbox.

 

by: DallasDAFPosted on 2009-08-17 at 07:23:02ID: 25114679

After further testing, it seems that even with a larger data set, it always misses the last record UNLESS I break with a break point or a msgbox.

 

by: thenelsonPosted on 2009-08-17 at 07:47:56ID: 25114925

One more try: Try adding this code where you placed the msgbox:

Dim intTimer As Integers

intTimer = Timer
Do
Loop While Timer - intTimer < 5

 

by: DallasDAFPosted on 2009-08-17 at 08:50:48ID: 25115642

thenelson,

That worked.  Any idea why though?  Also, do you think the msgbox approach is at all flawed.  Please explain, and thanks.

 

by: thenelsonPosted on 2009-08-17 at 09:47:13ID: 25116149

<Any idea why though?>
It is as timing issue. Some things are done asynchronously like links to spreadsheets.  This means that some operations occur in parallel to the code execution.  The do loop is providing some time for the asynchronous possess to complete.  I suggested the do loop based on time as a quick debug tool. Using a set time delay is not a good idea since the timing can change for different computers, networks, etc.  Better to wait until you know the  process is complete.  For this, something like:

.Open strSql, cn, adOpenStatic 'adLockOptimistic, adCmdText
Do
Loop Until rs!SomeField = Something expected  or  Loop While IsNull(rs!SomeField)

 

by: thenelsonPosted on 2009-08-17 at 09:49:55ID: 25116167

or better than  Loop While IsNull(rs!SomeField)
Loop Until Len(rs!SomeField & "") > 0
Takes care of zero length string and is empty.

 

by: acperkinsPosted on 2009-08-17 at 10:31:33ID: 25116466

>>I'm not sure what was different in what you did.<<
You did not notice how I commented out the use of the RecordCount porperty?  You reliance on that property is what is causing all your grief.  If you are into pain, that is fine, otherwise do not use it. Period.

 

by: DallasDAFPosted on 2009-08-17 at 10:41:41ID: 25116558

the .recordcount property was not the problem.  I was not controlling the loop by using the .recordcount property so why would that cause any trouble?  Plus, it's not the loop itself that is ending prematurely, but rather the data set being pulled was recognizing only 2 rows, and therfore .eof at the 2nd record.  I'm not sure that a "better loop" really takes care of this issue.

 

by: acperkinsPosted on 2009-08-17 at 10:43:06ID: 25116564

Whatever works for you.

Good luck.

 

by: DallasDAFPosted on 2009-08-18 at 10:15:58ID: 31616352

There is some timing issue, but this is not the ideal solution.

 

by: thenelsonPosted on 2009-08-18 at 10:20:53ID: 25125453

<but this is not the ideal solution.>
 Yes, see http:#a25116167 or http:#25116149 for a better solution.

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...