A popular source of debate between VBA programmers is the choice of whether to force people to declare variables (using the Dim command) or not. There are many people in both camps.
If you ask me then I will say "Yes, do declare variables". Why? Well several reasons really.
- When you declare a variable, it's an ideal place to add a comment describing what that variable actually is (in plain language). This is potentially valuable information for the next person who has to look at your code.
- If you use camel case for your variable names, e.g. MyVariable, then by declaring them the VB editor will automatically capitalise the appropriate letters when you press ENTER at the end of a line of code. This gives you an instant visual check - if something doesn't capitalise correctly then you've done something wrong!
- If you don't declare variables then typos are your worst enemy. Say you spell a variable name incorrectly somewhere in your code. VBA will automatically think you wanted a new variable, create it and then carry on. Often it will be obvious from the output that something is wrong, but tracking it down in the code can be a pain! And all because of a simple typo.
- If you ever decide to pick up another programming language then there's a good chance you'll be forced to declare all variables there. In my opinion it's worth getting into the habit as soon as you can.
- If you don't declare a variable then any variable you use will have Variant type. Some people will argue that this wastes memory. It does but these days we've got gigabytes of memory so - realistically - we aren't often going to run out of space. However if something should always be an integer then why not force it to be one? Wouldn't you want to know if you were expecting a whole number but the variable actually contained something silly, like "fish"?!
No comments:
Post a Comment