Avoiding Naming Conflicts
A naming conflict occurs when you try to create or use an identifier that was previously defined. In some cases, naming conflicts generate errors such as "
|
" or "
|
". Naming conflicts that go undetected can result in bugs in your code that produce erroneous results, especially if you do not explicitly declare all variables before first use.
You can avoid most naming conflicts by understanding the scoping, private module-level, and public module-level.
A naming conflict can occur when an identifier:
- Is visible at more than one scoping level.
- Has two different meanings at the same level.
For example, procedures in separate modules can have the same name. Therefore, you can define a procedure named
|
in modules named
|
and
|
. No conflicts occur if each procedure is called only from other procedures in its own module. However, an error can occur if
|
is called from a third module, and no qualification is provided to distinguish between the two
|
procedures.
Most naming conflicts can be resolved by preceding each identifier with a qualifier that consists of the module name and, if necessary, a project name. For example:
|
The preceding code calls the Sub procedure
|
and passes
|
as an argument. You can use any combination of qualifiers to differentiate identical identifiers.
Visual Basic matches each reference to an identifier with the "closest" declaration of a matching identifier. For example, if
|
is declared Public in two modules in a project (
|
and
|
), you can specify the
|
declared in
|
without qualification from within
|
, but you must qualify it as
|
to specify it in
|
. This is also true if
|
is in a different but directly referenced project. However, if
|
is in an indirectly referenced project, that is, a project referenced by the project you directly reference, references to the
|
variable named
|
must always be qualified with the project name. If you reference
|
from a third, directly referenced module, the match is made with the first declaration encountered by searching:
- Directly referenced projects, in the order that they appear in the References dialog box of the Tools menu.
- The modules of each project. Note that there is no inherent order to the modules in the project.
You can't reuse names of host-application objects, for example, R1C1 in Microsoft Excel, at different scoping levels.
Tip
Typical errors caused by naming conflicts include ambiguous names, duplicate declarations, undeclared identifiers, and procedures that are not found. By beginning each module with an Option Explicit statement to force explicit declarations of variables before they are used, you can avoid some potential naming conflicts and identifier-related bugs.