View Single Post
  #2   Report Post  
Posted to microsoft.public.excel.programming
Matthew Connor Matthew Connor is offline
external usenet poster
 
Posts: 17
Default Option Explicit and Arrays

Harlan Grove wrote:
Just caught a typo.

In Excel 97 VBE, the following general module code doesn't generate a compile
error.

'---- begin VBA ----
Option Explicit

Sub foo()
Dim n As Long
n = 5
ReDim y(1 To 5) '<- !!
MsgBox n
End Sub
'---- end VBA ----

Is the ReDim line an array variable declaration similar to Dim, or a statement,
or a hybrid? Does this work the same in 2K and XP?

Works as is in 2002 (XP).

It causes an error if it is changed to:
ReDim Preserve y(1 To 5)

Apparently this is a feature - I found in the help the following:
"Caution: The ReDim statement acts as a declarative statement if the
variable it declares doesn't exist at module level or procedure level.
If another variable with the same name is created later, even in a
wider scope, ReDim will refer to the later variable and won't
necessarily cause a compilation error, even if Option Explicit is in
effect. To avoid such conflicts, ReDim should not be used as a
declarative statement, but simply for redimensioning arrays."


Regards,

Matthew