VBA naming rules

This page details which naming rules apply in VBA for procedures, variables and other program elements and what compile errors occur if these rules are not followed.

A legal VBA procedure looks like below (procedure name, variable name). The typical use of CamelCase for readability and prefixing of the variable name with a short code indicating the variable type together are the so-called Hungarian convention which Microsoft also endorses for Visual Basic. The prefixing is actively supported by Code VBA add-in automatically adding the correct prefix - see VB naming conventions.


Sub My1stProcedure()
Dim strCustomerAddress2 As String

End Sub

You must use a letter as the first character

For example, if you declare a variable like this Dim 1 you will get compile error 'syntax error'.

Alternatively, if you try to name a procedure Sub 1, you will get 'compile error expected identifier'.

syntax error compile error expected identifier

Spaces and special characters not allowed

If you declare a variable like this Dim a b you will get compile error 'syntax error' again.

Alternatively, if you try to name a procedure Sub a b, you will get 'compile error expected end of statement'

compile error expected  end of statement compile error expected  end of statement

Generally, you can't use a space, period (.), exclamation mark (!), or the characters @, &, $, # in the name.

If you declare a variable like this Dim A#bc you will get compile error 'syntax error' again.

If you try to name a procedure Sub a#, you will get 'compile error expected identifier without syntax suffix'. This refers to an outdated (though still supported) feature of variables that you can assign there type using a special character suffix, saving typing 'As Double' which is where the suffix # stands for. However, as nobody uses this anymore, your collegues will not be happy with your code, so you'd better not use this.

May not be same as VBA keyword

If you declare a variable like this Dim If you will get compile error 'syntax error'.

If you try to name a procedure Sub If, you will again get 'compile error expected identifier'.

.

May only be used once in the scope

If you declare a variable with the same name twice you will get compile error 'Duplicate declaration in current scope'.

If a procedure with the same name already exists in a procedure you will get the compile error 'Ambiguous name'.

compile error duplicate declaration in current scope compile error ambiguous name