Friday 30 September 2011

To Declare or Not To Declare

If you're not familiar with declaring variables then please look up "Option Explicit" in VBA help or on your favourite web search engine first. This post is not about what that does - rather it concerns the choice of whether or not to use it.

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.
  1. 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.
  2. 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!
  3. 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.
  4. 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.
  5. 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"?!
Counter-arguments tend to focus on ease of use. E.g. why bother declaring when you don't have to? Personally I think it's a good discipline to get used to and once you've got it you'll actually find it's quite useful.

Welcome to .xls

Hi and welcome to my Excel Blog. Clearly there are masses of resources out and about on the interweb for Excel and VBA developers so why one more?  Well I've only recently started doing blogging (of sorts) on our company intranet and people seemed interested. So I figured I'd try a real blog out.

Sign up if you're interested and I'll share some thoughts and ideas with you.  I'm happy to discuss queries so fire away.  I can't promise to know all the answers but I will try :)