Free Lessons
Courses
Seminars
TechHelp
Fast Tips
Templates
Topic Index
Forum
ABCD
 
Home   Courses   TechHelp   Forums   Help   Contact   Merch   Join   Order   Logon  
 
Home > TechHelp > Directory > Access > Nested Loops < For Each Loop | VBA Loops >
Nested Loops
By Richard Rost   Richard Rost on LinkedIn Email Richard Rost   3 years ago

Nested Loops. Multiplication Tables. D&D Dice Rolls


 S  M  L  XL  FS  |  Slo  Reg  Fast  2x  |  Bookmark Join Now

In this Microsoft Access tutorial, you will learn how to effectively use nested loops. We will start by introducing what nested loops are and why they are useful in Microsoft Access. Then, we will look at the structure of nested loops, understanding the interaction between the inner and outer loop. We will build some multiplication tables and simulate dice rolls with a D&D character stat generator. Fun stuff!

Members

There is no extended cut, but here are the databases:

Prerequisites

VBA Loops Series

Links

Recommended Courses

Syntax

For X = 1 to 10
    For Y = 1 to 5
        ' Your Code Here
    Next Y
Next X

Learn More

FREE Access Beginner Level 1
FREE Access Quick Start in 30 Minutes
Access Level 2 for just $1

Free Templates

TechHelp Free Templates
Blank Template
Contact Management
Order Entry & Invoicing
More Access Templates

Resources

Diamond Sponsors - Information on our Sponsors
Mailing List - Get emails when new videos released
Consulting - Need help with your database
Tip Jar - Your tips are graciously accepted
Merch Store - Get your swag here!

Questions?

Please feel free to post your questions or comments below or post them in the Forums.

KeywordsNested Loops in Microsoft Access VBA

access 2016, access 2019, access 2021, access 365, microsoft access, ms access, ms access tutorial, #msaccess, #microsoftaccess, #help, #howto, #tutorial, #learn, #lesson, #training, #database, nested loops, loops in Access, nested loop structure, inner loop, outer loop, loop interaction, multiplication tables, dice rolls, D&D character stat generator, loop examples, Loop database, for loop, while loop, D&D Dice Roller, simulating dice rolls, total rolls, individual dice, ability scores, display results, Run-time error '9', subscript out of range

 

 

Comments for Nested Loops
 
Age Subject From
3 yearsSubscript out of rangeMatt Hall
3 yearsNested LoopsMichael Duncan

 

Start a NEW Conversation
 
Only students may post on this page. Click here for more information on how you can set up an account. If you are a student, please Log On first. Non-students may only post in the Visitor Forum.
 
Subscribe
Subscribe to Nested Loops
Get notifications when this page is updated
 
Intro In this video, we will talk about how to use nested loops in Microsoft Access VBA. I will show you how to combine loops like For Next and While loops, explain how nesting works for creating things like multiplication tables, and discuss best practices for managing variables and avoiding common pitfalls such as endless loops. We'll also look at some practical examples, including generating random Dungeons & Dragons stats using nested loops and arrays.
Transcript We've been learning a lot about loops, but did you know you can put multiple loops together? That's called nested loops. That's one loop inside of another one. We're going to talk about that today.

So we've covered For Next, While Wend, Do While, Do Until, For Each Next. I've read pretty much all the different loop types there are. Now we're going to talk about nested loops. It's putting two of them together, or more - two, three, eight, fifteen, however many you want, pretty much.

This is a developer level video. If you've never done any VBA programming before, watch this video. It's about 20 minutes long and it'll teach you everything you need to know to get started.

While you can nest pretty much any of these loops, we're going to focus on two of them today - the For Next loop and the classic While loop, which is the one I use most of the time.

If you haven't watched these videos, go watch these first, and we're going to do a little bit more dice rolling today. Dice rolling is really good for the loop example. So go watch these too. These are all free videos. They're on my YouTube channel and on my website. Go watch these guys and then come on back.

So, we learned about the basic structure of a For Next loop: for x = 1 to 10, do some stuff in the middle, and then Next. And that's if you have a single loop - that's going to run through this ten times.

We can nest these together. Inside of the x loop we can have another loop. Let's call it a y loop, and this one's going to run a hundred times. How many times total does this run? Well, ten times a hundred, so it's going to run a thousand times.

y is going to go from one to one hundred. Then x goes to two, y again goes from one to one hundred, x goes to three, and so on.

You might notice next to the Next there, I got the Next y and Next x. You don't normally have to do that, but I prefer doing that. It's actually optional. If you only have one loop, you really don't need it, but if you've got multiple loops I suggest putting them on there. It just makes your code more readable. Access doesn't care, VBA doesn't care, it'll just loop the innermost loop, but that makes your code a whole lot more readable, so I like doing that.

Make sure you do that, or you'll get in trouble. You'll go to the back of the class and stuff like that.

Let's take a look at our loop database we've been building. Let's make a new button in here. Let's do a nested For loop. Let's take this guy and make another button. Grab the For Next loop guy, drag it down here. We'll do "Nested For Next" - that's too big, so we'll just do "Nested For Next." You know this is a loop database by now.

Come on up here. We're going to say "Nested For" button, right-click build event. Let's do some multiplication tables. Multiplication tables give you an awesome way to show how nesting works.

Here's the example on my opening slide - right there. Let me bring it to my PowerPoint. See? So we've got rows and columns. Each row would be the x loop, one to ten, and then each column inside of that would be another loop, one to ten. You could do up to 12, up to 50, whatever, but this is a perfect example to show you a nested loop.

I'm going to put that back the way it was. There we go.

What's this going to look like? We're going to set some variables first. We need "Dim x as Long, y as Long." Then let's make a string so that we can just put the stuff in the string and then status out the string at once. So we'll say "s as String."

A lot of people say use meaningful names, and I agree. When you're building a real world database where you're running your business on it, don't use x and y unless it's for a real short loop iteration or something small in a local sense. If you're designing a customer database, don't use f for first name, use first name. But for examples like this, this is fine. Or if you've got a simple little x loop to do something inside, that's okay. A temporary string variable "s" - I've been doing that for years. Don't listen to those perfectionists.

Speaking of which, let's blank our status box. For those of you who didn't watch my status box video, that's this guy - it's the text box on the form that I used to display all the stuff. I have a separate status box video. If you watched the other videos, then you've watched that already too.

So, s equals blank - let's blank s. Always initialize your variables, folks. VB usually does it for you, but I used to program in C, and with C, you can't always count on that.

So our outer loop will say: "For x = 1 to 10" and then "Next x" down there. Always put your closing on first. That's just my opinion, but you're here to learn from me, so do what I tell you to do.

Inside that loop, we're going to say "For y = 1 to 10." Don't forget your indenting. Then "Next y."

In here is where the magic is going to happen. We're going to take our s variable and add a line to it. The line is going to be built piece by piece. We'll go across each line and make it look like this: 1, 2, 3, 4, and so on. If we're in the fives row, if x is 5, then this is going to look like 5, 10, 15, 20, etc. We're going to multiply x times y to get whatever value we're on.

So we're going to say in here: s = s & x * y & " " - so we're adding onto our s value, x times y, and then after that, add a space so we've got some space between the numbers. That's it, get rid of your empty spaces, and then we're all done. We'll status our s string.

Save it, do a quick Debug Compile, go back over to the database, close it, open it. Where's our button? Right there, "Nested For" button, ready, go. There you go. Look at that.

Now, we forgot to put a new line in there. So let's come back over here. We'll say s = s & [something]. After each y line, I want to put a new line character, so it's going to build this out: one, two, three... up to ten. After each y finishes, say s = s & vbNewLine. VB new line is a special character, it's actually two characters, but that puts the end on the line.

Save it, go back, run it again. There you go.

See, x starts at one, and then y goes one, two, three... to ten. Loop x is now two, so two times one, two times two, two times three, two times four, two times five, and all the way down the list. When x gets to 10 and y gets to 10, then we're done.

Now, when I used to teach this in my VB class, everybody always asks how to get this to line up right to look like it's in proper rows and columns. First of all, these guys are what you call TrueType fonts, which means the sizes aren't always the same between the letters. Like the lowercase letter l and a w - one is wider than the other. So you want to use a monospaced font, first of all.

Go into Design view. Let's make this a little bit bigger. Make this bigger, like this, so we've got some room to work with. We're going to change this guy's font to something like Courier New. All right. So now it's a monospaced font. If you run it now, it looks a little better.

Now we've got the problem where some numbers only take up one space, whereas some take up three. There are a couple things we could do. First, we could try to format the number with three digits. Come in here and right here, we're going to say: format that in the format with three digits, like this - "000". That's how you'd normally format a number with three digits. You need that one because the other formats say if there isn't a zero there, don't put a character there, but we need the character there. If you run it now, you'll get that. And that's technically correct, but it's not exactly what you're looking for. You don't want to see those leading zeros.

Here's the trick. Everyone loves this one when I show it. We're going to take x times y, we're going to add two spaces in front of it. Now, we're going to take this whole thing and take the rightmost three characters of that. Right(..., 3). So basically, you're padding it with spaces on the left, then the number. So you might get " 1", or you might get "100". Once you're done with that, take the rightmost three characters and you'll end up with " 1", " 12", "100", see how it is? It takes the rightmost three characters. That's just one of my little fancy tricks. Now when I run it, there you go. That's perfect. That's exactly what you want.

I've got videos that cover that Format function and the Right function and the string functions videos. I'll put links to those down below in the links section.

Now, you can do the same kind of thing with all the other loop types. Let's rewrite this as a While loop.

We have to maintain the variables, because with a For loop, Access takes care of the variables for you, initializes the variable, and it knows what the endpoint is. With a While loop, Do loop, or Do Until, all those other loops, you have to take care of the variables yourself.

Here, we have to say x = 1, and then "While x <= 10". Down here, there's your "Wend" - there is no "Next x" by the way. If you believe it, it gives you an error. It's just "Wend", so you have to be careful on which one is which. You can leave it like this if you want. You can have a While loop with a For loop inside it, or vice versa. You can mix and match these loops.

Same thing in here - you have to initialize y each time: y = 1 each time each loop you have to re-initialize it every time this starts. Then right here: "While y <= 10", and here's your "Wend" right there. Thank you, done.

Take a close look at it. What's missing? I've made this mistake myself thousands of times and had to restart Access and kill it with the Task Manager. Do you know why? Do you see it? What are we missing? We didn't increment our variables.

I'm popping this slide up so maybe it'll stick in your brain because even now, I still mess this up. Don't forget to increment your counters. I was going to do some kind of flashy video with the movie stuck in an endless loop and maybe some explosions, but I figured this is silly enough so that maybe it'll stick in your brain. Beware endless loops. You don't want to end up in Groundhog Day with Bill Murray, or what was that other one with Tom Cruise and Emily Blunt, Edge of Tomorrow? That was a really good movie. The ending was kind of meh, but I loved the movie.

You have to make sure you increment your counters. So here inside the While loop: y = y + 1, and inside this guy: x = x + 1. Now, we should be ready for prime time. Give it a quick Debug Compile.

Note to the Access team or any compiler guys, you should make it so they check for incrementers. I don't know how, have the debugger check it or something, but that'd be a nice little cool warning.

Ready? Let me just put some garbage in here so we can see that we're doing it. Ready? Click. There it goes, same thing, same results.

See, most of these loops, it's just a matter of writing it differently because of how your brain works. Pretty much all the loops do the same stuff. It's just phrasing it differently for how you want it to read. The computer doesn't care.

Let's put this guy to bed and look at our D&D character generator. This is the video from the random video, and all it does right now is generate six random ability scores for a D&D character - strength, intelligence, wisdom, and so on. How are we doing that? We covered this in the random video. We're just rolling dice. We made a function, we return the value, we're just putting three of them together and adding them. But we really have no control over the individual numbers. What if you wanted to do this with six dice and fifteen scores? You'd have to copy and paste all that, and that's annoying.

We can use a loop to do this instead. We have six ability scores and three dice per score - that sounds to me like a nested For loop or whatever loop you like.

Let's get rid of all this stuff.

We need some variables again: Dim x as Long, y as Long. Now I'm going to store each die roll in its own variable. You don't have to, but I'm going to. So we're going to say d as Long. We'll need a total for each stat, because we're going to roll three times - three dice - and we're going to add those three up and get a total for each stat so we can display that. So, total as Long. And just like we did last time, we're going to put each die roll in a string variable, s as String.

Randomize things up, set the stats box equal to blank.

We need two loops. The first loop is for six ability scores: For x = 1 to 6. That's for our ability scores. Next x. (My x is lowercase. I don't like it. Capitalize it and that should fix. Okay, good.) Now, inside here, the inner loop is for y = 1 to 3. Those are the dice rolls. Then Next y, in here, and we'll put our Next x down there.

There's our basic structure. s is going to be for each line. So inside the line in here, we're going to initialize it: s = "Stat 1", "Stat 2", "Stat 3" - we'll add names at the end of the video. I've got something special planned for you. For now, we're going to say "Stat" & x, so it'll be Stat 1, Stat 2, Stat 3, and so on, and a colon.

Then we're going to initialize our total: total = 0. For each stat, we're going to start at zero, and we'll add three dice to it.

Inside the y loop, this is where we're adding our dice rolls up. d = Die(6) - that's our die roll function, covered in the random video. Now that we've got a die rolled, we can say total = total + d.

Now let's add that to the line we're building. We've got Stat 1, and we're going to say s = s & d & " ". So it'll be Stat 1 6 5 4. The next line will be Stat 2 3 2 1, or whatever.

When each line is finished, out here, we're going to put the total on the end of it. s = s & " = " & total. Then for each line this time, you could put this all on a bigger string and status it out once if you want to. I'm just going to do it line by line. So we'll status s here. You could do it like we did in the other example and put a vbNewLine after the end of this, whatever you want. I'm going to show you something different in a minute.

Save it, throw in a Debug Compile, come back out, close it, open it, click it, boom. There you go. Remember, it goes backwards in the status box: Stat 1, 5 1 4 is ten, Stat 2, 5 5 3 is thirteen, and so on. That's pretty cool.

You could put commas after here or put plus lines in there, but then you'd have to have a special condition for the last one. That's up to you if you want to. I'm not going to do that right now. If you want to see that, bug me, post a comment down below in the comments section and I'll include it in a future video.

There's all kinds of fun you can have with this, by the way. You could do stuff where you roll four dice and drop the lowest one, or you roll six stats, or seven or eight stats and let them pick the best. Have fun with this stuff like I do. Let me know - I'll do more videos on it. Squeaky wheel gets the grease.

Now instead of that stat whatever, we've got six items here. I've got a list of six things - that to me is screaming "array." Remember my array video I did a couple days ago? This is optional. I didn't make it a prerequisite because you don't need to do this part, but go watch it if you want to learn more about arrays.

We could put the stat names in an array. Like this: dim statName as Variant. We're making an array, which is a single variable that holds a bunch of stuff. Then here we're going to say statName = Array("Strength", "Intelligence", "Wisdom", "Dexterity", "Constitution", "Charisma"). In order to use the Array function, it's got to be a Variant type. That's okay.

Now, instead of saying "Stat" & x, right here I can say statName(x), just like that. Save it, Debug Compile, everything looks fine. Let's go over here and run it.

Subscript out of range. What's going on? What does that mean? Debug. s = statName(x) is six. What's the problem here? Anybody know? Anybody think of it?

I only mentioned this briefly in the arrays video. I spend a lot more time on this in my full VB class. If you're dealing with an array and you're going to use the Array function like this, remember arrays by default are zero-based. Unless you specify the array goes from one to six, it's going to go from zero to five. And if you want to use the Array function, unfortunately, you have to do it like this with a Variant. You can't specify "one to six" in here. So you just have to know that you need to change your parameter a little bit. You have to make this from zero to five, because when the Array function loads these values into the array, it starts with zero, one, two, three, four, five. I didn't design it, folks. I just have to teach you how it works.

Now, if you save it, come back out here, run it, everything works perfectly. Same results. It's the same thing, it just changed the lower and upper bounds of the array. That's all.

What if you want these guys to display in the right order on here? They're backwards because the status box works backwards as well. You can either change the order of them in the array as they're loaded in or you can just flip your loop, go from five to zero step negative one. We talked about that in the For Next video. Now if you run it, they're in the right order.

And yes, that is the correct order for D&D players. That is the original order. I'm sticking to it. None of this Strength, Dexterity, Constitution, Intelligence, Wisdom, Charisma - in second edition they flip them around so the top three stats are your physical stats and then your mental stats or whatever down below it. No, this is how Gygax wanted it.

If you like this kind of stuff, if you like learning with me, and you want to learn more about programming, I spent a lot more time covering this kind of stuff in my full developer classes. We go over all kinds of different examples and some fun stuff.

If you like learning with me, well, this is how you can learn more. Check it out; I'll put a link down below on my website and you can find out all you want. If you have any questions, of course, feel free to contact me or post them in the comments section down below.

Don't forget to increment your counters. If this slide looks familiar, it's because it's the same one I used for "Backup Your Data." For those of you who've been following me for a few years now, you've probably seen that slide before - I just recycled it.

That's going to be your TechHelp video for today. I hope you learned something and had some fun. I know I had some fun. Live long and prosper, my friends. I'll see you next time.
Quiz Q1. What is a nested loop?
A. A loop with a condition checked only once
B. Two or more loops where one is placed inside another
C. A loop that only runs once
D. A loop that only works for rolling dice

Q2. In VBA, which of the following is TRUE about nesting loops?
A. You can only nest For Next loops, but not While loops
B. You can nest loops of any type, including For, While, and Do loops
C. You can only have two loops nested
D. Nesting loops is not allowed in VBA

Q3. If you nest a For loop inside another For loop, and the outer loop runs 10 times while the inner loop runs 100 times, how many times does the innermost code run?
A. 100 times
B. 10 times
C. 1,000 times
D. 110 times

Q4. Why does the instructor recommend using Next y and Next x in nested For loops?
A. It is required by VBA to avoid errors
B. It helps keep code readable in complex nested structures
C. It makes the code run faster
D. It prevents the use of While loops

Q5. What is a good real-world example for demonstrating nested loops, as mentioned in the video?
A. Calculating the average of a list
B. Building multiplication tables
C. Fetching user input once
D. Printing a single message to the screen

Q6. When creating a multiplication table with nested loops, what calculation does the code perform in the innermost part of the loop?
A. Adds x and y
B. Divides y by x
C. Multiplies x times y
D. Subtracts x from y

Q7. What issue can arise with display alignment when printing multiplication tables in a text box?
A. Numbers will always be aligned by default
B. Monospaced fonts make alignment worse
C. Different numbers have different width characters in most fonts
D. VBA does not allow control over font choice

Q8. What trick does the instructor use to make numbers line up properly in the multiplication table output?
A. Pads numbers with leading zeros using the Format function
B. Pads numbers with spaces on the left and then uses the Right function to trim to a fixed width
C. Always displays numbers as strings
D. Uses a random function to space out the numbers

Q9. In a While loop, what must you remember to do that differs from For Next loops?
A. Declare all variables globally
B. Initialize and increment the counter variables manually inside the loop
C. Use vbNewLine after each iteration
D. Use Next instead of Wend

Q10. What will happen if you forget to increment your loop counter in a While loop?
A. VBA will automatically fix the issue
B. The loop will never run
C. The loop will run forever, causing an endless loop
D. The loop will skip to the end immediately

Q11. In the dice-rolling D&D example, what is indicated as a better approach than copying and pasting code to simulate rolling for multiple stats?
A. Use a nested loop structure to iterate over scores and dice rolls
B. Write a single static line of code for each roll
C. Roll all dice at once in a single command
D. Use only While loops, never For loops

Q12. What is the advantage of storing stat names (like "Strength", "Intelligence", etc.) in an array?
A. Stat names must change every loop iteration
B. You can easily reference each stat by its index in the loop
C. It prevents loops from running
D. It is required by VBA to display strings

Q13. What important difference about arrays created with the Array function in VBA does the instructor mention?
A. They are one-based by default
B. They are zero-based by default
C. They cannot store strings
D. They require the use of For Each loops

Q14. If you loop through statName = Array("Strength", "Intelligence", "Wisdom", ...) with x from 1 to 6, what error will you get in VBA?
A. Type Mismatch
B. Subscript out of range
C. Division by zero
D. Syntax error

Q15. To ensure the proper order when looping backward through an array from highest to lowest index, which loop structure is correct?
A. For x = 0 to 5
B. For x = 6 to 1 Step -1
C. For x = 5 to 0 Step -1
D. For x = 1 to 6

Q16. What is the main point emphasized about writing nested loops, regardless of the language or loop type?
A. Choosing descriptive variable names above all else
B. Proper initialization and incrementing of loop counters
C. Using only For loops instead of While loops
D. Avoiding the use of arrays at all costs

Q17. When using nested loops for dice rolling in the D&D example, what does the inner loop represent?
A. It loops through individual ability scores
B. It loops through each dice roll for the current stat
C. It checks if the die roll is valid
D. It initializes all variables

Q18. What practical suggestion does the instructor give regarding code readability and maintenance with temporary variables like x, y, or s?
A. Never use short variable names
B. Using short variable names is fine for small, local examples
C. Always use cryptic names
D. Only use single-letter variable names for everything, including databases

Q19. What is the consequence of not properly matching loop start and end statements (e.g., For/Next or While/Wend) in nested structures?
A. VBA will automatically correct the issue
B. You may confuse yourself or other developers, making code hard to read and maintain
C. It improves program speed
D. It only causes aesthetic problems, but no technical errors

Q20. According to the instructor, what is a common pitfall in writing While or Do loops which is less of an issue in For loops?
A. Forgetting to set initial values for counters and increment them each loop
B. Writing loops that are too short
C. Missing a Next statement
D. Failing to declare string variables

Answers: 1-B; 2-B; 3-C; 4-B; 5-B; 6-C; 7-C; 8-B; 9-B; 10-C; 11-A; 12-B; 13-B; 14-B; 15-C; 16-B; 17-B; 18-B; 19-B; 20-A

DISCLAIMER: Quiz questions are AI generated. If you find any that are wrong, don't make sense, or aren't related to the video topic at hand, then please post a comment and let me know. Thanks.
Summary Today's TechHelp tutorial from Access Learning Zone is focused on the concept of nested loops in Microsoft Access VBA. So far, we have covered a wide range of loops, including For Next, While Wend, Do While, Do Until, and For Each Next. Now, I want to explain how you can combine multiple loops, placing one inside another, to achieve more complex iteration. This concept is known as "nesting" loops, and you can nest as many as you need, whether that's two or fifteen.

If you are new to VBA programming, I recommend checking out my beginner tutorial to get up to speed. It's about twenty minutes and will give you a solid foundation before tackling more advanced topics like this one.

Although nesting is possible with any of the loop types, today I'll focus on the For Next loop and the While loop, both of which are commonly used in real-world Access development.

Before diving into the coding details, make sure you are familiar with the basics of loops. I often use dice rolling examples to illustrate these concepts, as they provide clear, practical demonstrations. All of my introductory loop videos are available for free, both on YouTube and my website. If you need a refresher, those are great resources.

Let's recap the structure of a simple For Next loop: If you set x to go from 1 to 10, the loop will execute ten times. By placing another loop inside it, such as y ranging from 1 to 100, you create a nested loop. The total number of iterations will be the product of these two ranges, so in this example, 10 times 100, or 1,000 iterations. For each increment of x, y cycles through its entire range.

In my examples, I always use "Next y" and "Next x" at the end of each loop. While not strictly required by VBA, it helps keep your code readable, especially when loops are nested. It may be optional, but I highly recommend this practice.

Now, let's look at a practical example using our loop database. Imagine building a multiplication table using nested For loops. The outer loop represents the rows (let's call it x, from 1 to 10), and the inner loop represents the columns (y, also from 1 to 10). You start by declaring your variables—x, y, and a string variable s to accumulate the output. In quick, simple examples like this, using short variable names is acceptable, but always use descriptive names in real-world business applications.

I also recommend initializing your variables. Although VBA often does this automatically, habits from languages like C tell me not to take this for granted.

With the structure in place, the code for building the multiplication table is straightforward: for each number from 1 to 10, multiply x by y, append it to the string with a space, and after each row, add a new line character. When outputting to a control such as a form's status box, using monospaced fonts like Courier New can help with alignment. To make sure your table is visually tidy, I use a trick with the Right function. By padding numbers with spaces and then extracting the rightmost three characters, you ensure each cell in your table lines up perfectly, regardless of whether the number is one or three digits long. If you're interested in the details of string formatting, my video tutorials provide plenty of additional demonstrations.

Of course, it's not only the For Next loop that supports nesting. Other loop types, such as While loops, work similarly, but you are responsible for initializing and incrementing the counters yourself. Forgetting to increment leads to endless loops, which is a famous debugging headache. I cannot stress enough: always increment your counters!

Let's take a look at how this principle applies to another example, such as generating ability scores for a Dungeons and Dragons character. Previously, the code for this just added up random dice values a few times, but with nested loops, you can automate this for any number of stats and dice. For instance, using variables x and y for stat and die counts allows you to scale up easily. Place the loops accordingly: the outer one for ability scores, and the inner one for dice rolls. Collect each die value, add it to a running total, and construct the output string. You can build and display the results line by line, or collect them first and then output, depending on your needs.

For further refinement, using an array lets you substitute "Stat 1," "Stat 2," and so on with meaningful names like Strength, Intelligence, Wisdom, Dexterity, Constitution, and Charisma. Remember, arrays in VBA created with the Array function are zero-based. This means if you're looping from 1 to 6, you'll get a "subscript out of range" error, because valid indexes are 0 to 5. Adjusting your loops or the array indexing solves this issue neatly. You can also reverse the array or flip the loop order to control the display order, a feature D&D fans might appreciate to stick with the original stat sequence as intended by Gygax.

If you want to learn more about techniques like string formatting, arrays, or random number generation, I've got dedicated videos linked on my website for those topics.

In summary, nested loops are powerful tools in VBA programming, enabling you to iterate over multidimensional data, automate repetitive tasks, and create structured outputs. Whether you use For Next, While, Do While, or mix and match them, the most important practice is to manage your loop variables carefully, always increment your counters, and take care with array bounds.

You can find a complete video tutorial with step-by-step instructions on everything discussed here on my website at the link below.

Live long and prosper, my friends.
Topic List Concept of nested loops in VBA

Creating nested For Next loops

Multiplication tables using nested loops

Variable initialization for nested loops

Building and displaying formatted output with nested loops

Using monospaced fonts for alignment in output

Formatting numbers for column alignment

Padding numbers with spaces using Right function

Rewriting nested loops using While Wend loops

Manually incrementing variables in While loops

Avoiding infinite loops in VBA

Using nested loops in a dice rolling example

Generating D&D ability scores with nested loops

Summing dice rolls within nested loops

Displaying roll results and totals on a form

Using arrays to store and reference stat names

Adjusting for zero-based arrays in VBA

Reversing loop order for display purposes
 
 
 

The following is a paid advertisement
Computer Learning Zone is not responsible for any content shown or offers made by these ads.
 

Learn
 
Access - index
Excel - index
Word - index
Windows - index
PowerPoint - index
Photoshop - index
Visual Basic - index
ASP - index
Seminars
More...
Customers
 
Login
My Account
My Courses
Lost Password
Memberships
Student Databases
Change Email
Info
 
Latest News
New Releases
User Forums
Topic Glossary
Tips & Tricks
Search The Site
Code Vault
Collapse Menus
Help
 
Customer Support
Web Site Tour
FAQs
TechHelp
Consulting Services
About
 
Background
Testimonials
Jobs
Affiliate Program
Richard Rost
Free Lessons
Mailing List
PCResale.NET
Order
 
Video Tutorials
Handbooks
Memberships
Learning Connection
Idiot's Guide to Excel
Volume Discounts
Payment Info
Shipping
Terms of Sale
Contact
 
Contact Info
Support Policy
Mailing Address
Phone Number
Fax Number
Course Survey
Email Richard
[email protected]
Blog RSS Feed    YouTube Channel

LinkedIn
Copyright 2026 by Computer Learning Zone, Amicron, and Richard Rost. All Rights Reserved. Current Time: 3/7/2026 1:19:04 AM. PLT: 2s
Keywords: TechHelp Access nested loops, loops in Access, nested loop structure, inner loop, outer loop, loop interaction, multiplication tables, dice rolls, D&D character stat generator, loop examples, Loop database, for loop, while loop, D&D Dice Roller, simula  PermaLink  Nested Loops in Microsoft Access VBA