My For/Next Loop is going too far - why?

TheRedCardinal

Active Member
Joined
Jul 11, 2019
Messages
250
Office Version
  1. 365
  2. 2021
Platform
  1. Windows
I have a really simple code:

VBA Code:
For Counter = 1 To UBound(SCols, 1)

    FinalArray(1, Counter) = SCols(Counter, 1)

Next Counter

The size of my arrays (as per the locals window) are:
  • Final Array, 1 to 133, 1 to 14
  • SCols, 1 to 14, 1 to 3
When I hover over "UBound(SCols,1) I get 14.

I know that the counter will loop to 15 but then shouldn't execute the code inside the For/Next loop.

I use these loops all the time and haven't seen this issue before.

But now my counter is 15 and it's trying to populate my FinalArray at (1,15) which obviously doesn't exist.

Have I done something very stupid?

****Update****

I have just stepped through and it's even more strange. When it gets to the code above, Counter is Empty.
In the 1st iteration of the loop, it is set to 14, and not 1?

****Update 2****

I went back to basics and declared my variables (I didn't originally because this is just testing code) and declared Counter as Long and now it seems to work ok, but why?
 

Excel Facts

What is the fastest way to copy a formula?
If A2:A50000 contain data. Enter a formula in B2. Select B2. Double-click the Fill Handle and Excel will shoot the formula down to B50000.
Long is the most efficient for Loops. VBA has less thinking in terms of worrying about busting the maximum and it is an integer. VBA could be storing the counter (variant) as something other than an integer. I tried to duplicate you problem and could not get the issue you have.
 
Upvote 0

Forum statistics

Threads
1,223,229
Messages
6,170,881
Members
452,364
Latest member
springate

We've detected that you are using an adblocker.

We have a great community of people providing Excel help here, but the hosting costs are enormous. You can help keep this site running by allowing ads on MrExcel.com.
Allow Ads at MrExcel

Which adblocker are you using?

Disable AdBlock

Follow these easy steps to disable AdBlock

1)Click on the icon in the browser’s toolbar.
2)Click on the icon in the browser’s toolbar.
2)Click on the "Pause on this site" option.
Go back

Disable AdBlock Plus

Follow these easy steps to disable AdBlock Plus

1)Click on the icon in the browser’s toolbar.
2)Click on the toggle to disable it for "mrexcel.com".
Go back

Disable uBlock Origin

Follow these easy steps to disable uBlock Origin

1)Click on the icon in the browser’s toolbar.
2)Click on the "Power" button.
3)Click on the "Refresh" button.
Go back

Disable uBlock

Follow these easy steps to disable uBlock

1)Click on the icon in the browser’s toolbar.
2)Click on the "Power" button.
3)Click on the "Refresh" button.
Go back
Back
Top