I am constructing my first major program in VBA (With some help from SO). The beginning of it is below, and I am adding blocks of code in as structured a way as possible. Having read about the importance of using 'Option Explicit' though, I inserted it and started to declare all my variables. Running the program gave - 'Compile Error: Variable not Defined'.
I have tried deleting and re-entering declarations in case the problem was caused by me adding 'Option Explicit' after starting on the code, as well as removing the UDF and adding that back in, but without success.
Commenting out 'Option Explicit' does away with the error message and the subsequent blocks of code run exactly as designed.
EDIT:I should have said that the error always occurs with 'iLoopControl'.
Option Explicit
'UDF to roll a number of Dice of specified size and total them
Function Dice(NoOfDice, DiceSize)
Dice = 0
For iLoopControl = 1 To NoOfDice
Dice = Dice + WorksheetFunction.RandBetween(1, DiceSize)
Next
End Function
Sub MercOne()
Randomize
Dim Merc(86)
Dim Temp As Integer, TechLevel As Byte, ArmOfService As Byte
Dim Year As Byte, YearCount As Byte
Dim GenAssignment As Variant, UnitAssignment As Variant
Dim SpecAssignmentSwitchEnd As Byte, Roll As Byte
Dim Rank As Variant, NoOfDice As Variant, DiceSize As Byte
Dim GenAssignmentSwitchInt As Byte, GenAssignmentSwitchOff As Byte
Dim CharacterNumber As Long, iLoopControl As Long
Option Explicit
means you must explicitly declare all variables and their types before using them. If you don't include the Option Explicit
declaration, then VBA will just create Variant
type variables whenever it encounters a new identifier.
So for example, you need to include Dim iLoopControl as Integer
if you have declared Option Explicit
:
Option Explicit
Dim iLoopControl As Integer
For iLoopControl = 1 To NoOfDice
Dice = Dice + WorksheetFunction.RandBetween(1, DiceSize)
Next
If you didn't include Option Explicit
then you could just use iLoopControl
without using the Dim iLoopControl as Integer
to declare it.
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments