473,854 Members | 1,802 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Inefficient Loop

6 New Member

I'm trying to simplify and make this piece of code more efficient (basically would like to remove the 2nd loop); any suggestions?


Expand|Select|Wrap|Line Numbers
  1.     Dim db As Database, rst1 As Recordset, rst2 As Recordset, qry1 As String, qry2 As String
  2.     Dim intCurrentProgress As Integer, intTotalWidth As Integer, intProgressBarMax As Integer
  4.     q = MsgBox("Are you sure you want to update all ranks?", vbExclamation + vbOKCancel)
  5.     If q = vbCancel Then Exit Function
  7.     qry1 = "SELECT DISTINCT tblStudents.StudentID, tblStudents.RankID FROM tblStudents INNER JOIN tblGradingResults ON tblStudents.StudentID = tblGradingResults.StudentID"
  11.     Set db = CurrentDb()
  12.     Set rst1 = db.OpenRecordset("qryLastGradingPerStudent")
  13.     intProgressBarMax = rst1.RecordCount
  15.     SysCmd acSysCmdInitMeter, "Updating: ", intProgressBarMax
  16.     If Not rst1.EOF Then
  17.         rst1.MoveFirst
  18.         Do Until rst1.EOF
  20.         SysCmd acSysCmdUpdateMeter, intCurrentProgress
  22.         qry2 = "SELECT tblStudents.StudentID, tblStudents.RankID, tblStudents.LastGrading FROM tblStudents WHERE (((tblStudents.StudentID)=" & rst1!StudentID & "))"
  23.         Set rst2 = db.OpenRecordset(qry2)
  24.             rst2.Edit
  25.                 rst2!RankID = rst1!RankID
  26.                 rst2!LastGrading = rst1!GradingDate
  27.                 rst2.Update
  28.             rst2.Close
  29.                 Set rst2 = Nothing
  32.             'update Progress Barr
  33.             intCurrentProgress = intCurrentProgress + 1
  34.         rst1.MoveNext
  35.         Loop
  36.     End If
  38.     rst1.Close
  39. '    rst2.Close
  40.     Set rst1 = Nothing
  41.     Set rst2 = Nothing
  42.     Set db = Nothing
Feb 19 '12 #1
6 1784
12,516 Recognized Expert Moderator MVP
Is there a reason you're doing it with a recordset instead of using an update query?
Feb 20 '12 #2
6 New Member
I did, but got an error: "Operation must use and updateable query"; hence why I used the recordset.
Feb 20 '12 #3
2,322 Recognized Expert Moderator Top Contributor
The reason it is not updatable is because you are using the keyword Distinct in your SQL, which also leads me to wonder if your data is properly normalised since you feel you need the distinct keyword.

I agree with Rabbit that from what you have presented here, it seems more like something for an update query,but we would need more details on your table design to say anything for sure.

I would still like however to answer your question.
In terms of making your code more efficient, you need to move the second recordset opening out of the loop, and then use rst2.findfirst and rst2.findNext combined with rst2.Nomatch (use the help function to read about the 3 functions) inside the loop.
Feb 20 '12 #4
6 New Member
Thanks for your answer Smiley. Qry1 is no longer required (I forgot to delete it from the code). The table structure is quite complex and can't be changed at this point of time.

I'm not sure to understand how to use the "find first" and "find Next" option, could you please give me more details?

Feb 20 '12 #5
2,322 Recognized Expert Moderator Top Contributor
I still need more info on your table structure to give you a proper answer. At best I would be guessing and probably confusing you.

Imagine however a tbl_Orders (with primary Key: PK_Order) and a tbl_OrderDetail s (With Foreign Key FK_Order) in which we would want to loop through the orders shipped today, specifying that each item was shipped succesfully.
Expand|Select|Wrap|Line Numbers
  1. Dim cDB as dao.Database
  2. Dim rsOrder as Dao.RecordSet
  3. Dim rsOrderDetails as Dao.Recordset
  4. set rsOrder=cDB.OpenRecordset("SELECT tbl_Order.PK_Order Where dt_OrderDate=Date()",dbopendynaset)
  5. Set rsOrderDetails =cdb.OpenRecordset("tbl_OrderDetails",dbOpenDynaset)
  7. dim strCriteria as string
  8. Do while not rsOrder.EOF
  9.   strCriteria="FK_Order=" & rsOrder!PK_Order
  10.   rsOrderDetails.FindFirst strCriteria
  11.   Do while NOT rsOrderDetails.Nomatch
  12.     rsOrderDetails.Edit
  13.       rsOrderDetails!b_Shipped=True
  14.     rsOrderDetails.Update
  16.     'Move to next match
  17.     rsOrderDetails.FindNext strCriteria
  18.   Loop
  19. Loop
  22. 'Cleanup
  23. set cDb=Nothing
  24. set rsOrder=nothing
  25. set rsOrderDetails=nothing
Feb 20 '12 #6
6 New Member
FindFirst works like a charm, speed gain is great. Thanks for your help.

Feb 21 '12 #7

Sign in to post your reply or Sign up for a free account.

Similar topics

by: Aaron | last post by:
Is there a way I can loop through everything that is in session?
by: Andrew Young | last post by:
How do I loop thru a result set Without using a curosr?
by: bourgon | last post by:
Working on some new code, I'm coming across WHILE loops used instead of cursors. I was curious if anyone had any stats on how the speed of doing this compares to the speed of a cursor. I typically avoid cursors for performance sake, but I'm not sure how this avoids the speed hit of a cursor, since it's doing essentially the same thing. Many thanks.
by: TrintCSD | last post by:
How can I reset the collections within a foreach to be read as a change from within the foreach loop then restart the foreach after collections has been changed? foreach(string invoice in findListBox.listBox2.Items) { listBox2.Items count changed, restart this foreach } Thanks for any help.
by: Javaman59 | last post by:
Using local declarations within a block often makes code more readable, but is it less efficient? eg... void P() { while (...) { int i = ...; bool b = ...; .... } }
by: Frederick Gotham | last post by:
Is the domestic usage of the C "for" loop inefficient when it comes to simple incrementation? Here's a very simple program that prints out the bit-numbers in a byte. #include <stdio.h> #include <limits.h> #include <stdlib.h> int main(void) {
by: silversurfer2025 | last post by:
Hello everybdy, I am a little confused for the following reason: In my code I used a simple for-loop in order to initialize a 2D-array of floats to zero. Because of efficiency reasons, I changed it to use memset and I get totally different results.. How can this be? Here is the example: float gaborfilter;
by: Doug_J_W | last post by:
I have a Visual Basic (2005) project that contains around twenty embedded text files as resources. The text files contain two columns of real numbers that are separated by tab deliminator, and are of different lengths (e.g. usually between 25 and 45 rows. The columns in each file have the same length). The text files have been numbered sequentially e.g. cb0, cb1, cb2 and so on. I would like to read the data from each text file into...
by: =?Utf-8?B?YmJn?= | last post by:
Hi all, I wanted to go through each entry(?) of ArrayList and remove some particular entry. So I tried following but it throws exception at runtime: foreach (myEntry entry in myArrayList) { // do something... if (entry.fieldA == 0)
by: Alex Snast | last post by:
Hello I'm new to python and i can't figure out how to write a reverse for loop in python e.g. the python equivalent to the c++ loop for (i = 10; i >= 0; --i)
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.