Re: Run-time Error Every Other Time The Macro Runs
Quote from gmccreedy
It a nut shell...it forces you to declare all of your variables. Its not necessary, but I reccomend it. It helps if you make a simple error...will trap it for you.
I'll disagree happily with GMc! It is a requirement. It is a real good development aid.
To expand on what he said,
Options Explicit requires that you declare using the Dim statement any variables that you use.
Going one step further, when you declare your variables you should also state their type. This includes function modules and subroutine parameters. So this code is bad:
Sub My_Sub(Arg1, Arg2)
Function My_Func(Arg1, Arg2)
Dim My_Var
This code is good:
Sub My_Sub(Arg1 as String, Arg2 as Long)
Function My_Func(Arg1 as Integer, Arg2 as User_Type)
Dim My_Var as Long
The reasons for this:
Option Explicit
[INDENT]Option explicit makes you declare all the variables that you use. This prevents bugs from entering your code caused by typo's in variable names. For example accidentally typing My_Var0 rather than My_VarO would be caught by this[/INDENT]
Typing your variables
[INDENT]Typing your variables has a few effects. From the development side it prevents errors because the arguments you call a subroutine with must exactly match the formal parameters.
It increases the speed at which your macros run. When VBA calls a subroutine, if the variables are untyped, it must determine the type of variables the subroutine requires and then coerce the actual arguments to those types.
Similarly when you use intrinsic functions, if you use a variable that is not typed or not typed correctly, the system has to again coerce the parameter to the formal parameters type.
If you do type all your variables and parameters, then these two steps do not occur, resulting in less time being spent doing this chore by the macro. This does not have much of an effect in straight code, but imagine a 10,000 iteration loop having to do these conversions all the time.
[/INDENT]
Regards
Rich