|

Visual Basic Naming Rules and Tips

This is an excerpt from Microsoft Excel Visual Basic Help, with tips and corrections.

Use these rules when you name procedures, constants, variables, and arguments in Visual Basic:

  • You must use a letter as the first character.
  • You can’t use a space, period (.), exclamation mark (!), or the characters @, &, $, # in the name. (Microsoft doesn’t say so, but you also cannot use ^, *, +, -, /, \, |, <, >, quotes, any kind of brackets, or any punctuation mark.  You can use the underscore, “_” –see the last tip below.  You can use the characters !, @, #, $, %, and & at the end of variable names to specify the variable type)
  • Name can’t exceed 255 characters in length.
  • Generally, you shouldn’t use any names that are the same as the functions, statements, and methods in Visual Basic. You end up shadowing the same keywords in the language. To use an intrinsic language function, statement, or method that conflicts with an assigned name, you must explicitly identify it. Precede the intrinsic function, statement, or method name with the name of the associated type library. For example, if you have a variable called Left, you can only invoke the Left function using VBA.Left
  • You can’t repeat names within the same level of scope. For example, you can’t declare two variables named Age within the same procedure. But you can declare a private variable named Age and a procedure-level variable named Age within the same module.  (Doing this may cause confusion and needless debugging.)

1.        Capitalization and Case-Sensitivity

Visual Basic isn’t case-sensitive, but it preserves the capitalization in the statement where the name is declared.

If you declare variables with the same spelling in multiple scopes, VB uses the most recent capitalization.  Thus, if you defined age& at module level, then Age# in Sub Test1, and finally AGE$ in Sub Test2, the result will be:

Again, using variables with the same spelling in multiple scopes is best avoided. Worse yet, is making them different variable types –in this example, long integer, double, and string!

2.        Tip: Avoid Mis-Spelling Variable Names

When you declare variables, start your variable names with a capital letter.  Or follow the naming convention proposed here, which will give you Mixed Case.  Then, when typing your code, type your variable names all in lower case.  If Visual Basic capitalizes the variable correctly when you leave that line, it has recognised it.  If it stays in lower case, you have a spelling error.

3.        Tip: Use Capitalization and the Underscore

When you name an object in Visual Basic, you can make the name easier to understand in two ways. One is with judicious capitalization.  A date variable defined as daDateOfBirth will be more obvious than dateofbirth.  But even better may be daDate_of_Birth, using the underscore character “_” to represent spaces, which are not allowed.

Similar Posts