PDA

View Full Version : ReDim scope



MamboKing
06-29-2008, 09:59 PM
I see this wieird behavior of ReDim in VBA.

I've a Public Vals_m#()

hence it should be visible everywhere in the module.

Executing the code I get: "Run Time Error 9 - Subscript out of range"

I understood that it's caused by a ReDim Vals_m(N)

This ReDim is instantiated into Sub1 that calls Sub2, both in the same module whith Public Vals_m#().

The error certainly occurs in Sub2 when I use Vars_m() first.

It really seems that the error is caused by the fact that Sub2 does not see the re-dimension of the array.

In fact, if I move ReDim Vals_m(N) into Sub2, the error disapperas!

Should't the ReDim of public array present the new dimensions everywhere in the Module?

Bob Phillips
06-30-2008, 09:07 AM
I am not seeing the problem with some code I just knocked up.

Can you post a code example?

MamboKing
06-30-2008, 09:25 AM
Can you post a code example?

No, I cannot...

Last night I fought with it for hours and had to change ReDim locations to make the code working.

I was now trying to replicate the problem for you, hence I restored the original locations or ReDim.

Everything is working fine regardless of the location of ReDim... :doh:

Let's see by the end of the day what happens...

MamboKing
06-30-2008, 02:32 PM
Run Time error 9: Subscript out of range.

I posted the Excel file here:

http://sites.google.com/a/piac3ntini.net/sharingdocs/Home/ReDim_location.xls (http://sites.google.com/a/piac3ntini.net/sharingdocs/Home/ReDim_location.xls)

Click on the button “Price The Binary” and the error will pop-up.

The VBA will highlight the location that produces the failure.

Just few lines below (in the Sub hierarchically one level higher) there are two ReDim:

1) ReDim Vals_m#(0 To NS)
2) ReDim Vals_md1#(0 To NS)

The error will disappear if 1) gets moved into the Sub where the error occurs.

But then a second, similar error will appear.
This will go away if 2) gets moved just few line below, just below the two Call statements.

I’d appreciate any hint!

Bob Phillips
06-30-2008, 03:11 PM
You are doing the ReDim before NS gets set. NS gets set to 100 in MtNS_calc, so when you yo ReDim it NS is 0.



ReDim Vals_m#(0 To NS)
ReDim Vals_md1#(0 To NS)

Call MtNS_calc(T2Expry, NofSsteps, sigmad, sigmap, ir)

MamboKing
06-30-2008, 03:16 PM
:wot Cannot say how I feel...

But, Thanks a bunch!

Seriously.