Ambiguous name detected vba что за ошибка
Перейти к содержимому

Ambiguous name detected vba что за ошибка

Ambiguous name detected

The identifier conflicts with another identifier or requires qualification. This error has the following causes and solutions:

More than one object in the same scope may have elements with the same name.

Qualify the element name by including the object name and a period. For example:

Module-level identifiers and project-level identifiers (module names and referenced project names) may be reused in a procedure, although it makes programs harder to maintain and debug. However, if you want to refer to both items in the same procedure, the item having wider scope must be qualified. For example, if MyID is declared at the module level of MyModule , and then a procedure-level variable is declared with the same name in the module, references to the module-level variable must be appropriately qualified:

An identifier declared at module-level conflicts with a procedure name. For example, this error occurs if the variable MyID is declared at module level, and then a procedure is defined with the same name:

In this case, you must change one of the names because qualification with a common module name would not resolve the ambiguity. Procedure names are Public by default, but variable names are Private unless specified as Public.

For additional information, select the item in question and press F1 (in Windows) or HELP (on the Macintosh).

Support and feedback

Have questions or feedback about Office VBA or this documentation? Please see Office VBA support and feedback for guidance about the ways you can receive support and provide feedback.

Why is VBA saying that it has found an 'ambiguous name'?

When compiling some code (declarations shown below) I get the error message ‘Compile Error: Ambiguous name detected. SixTables’. I have looked here and elsewhere but cannot find anything that matches my problem. What appear to be the most common causes of this error, declaring two variables with identical names or giving the same name to a function and the sub that it is called from, do not apply. And yes, I know I could just change the name to something the system was happy with, but (1) I wouldn’t learn what I’m doing wrong, and (2) I chose that name for a reason — it fits its purpose exactly 🙂

EDIT: I’m so embarrassed that I can hardly bring myself to explain what the problem was. I knew I hadn’t duplicated a name, since I was only using it once — as a function! Thanks all for your help, I’m now going to go and hide my face in shame.

2 Answers 2

  1. More than one object in the same scope may have elements with the same name.

Module-level identifiers and project-level identifiers (module names and referenced project names) may be reused in a procedure, although it makes programs harder to maintain and debug. However, if you want to refer to both items in the same procedure, the item having wider scope must be qualified. For example, if MyID is declared at the module level of MyModule , and then a procedure-levelvariable is declared with the same name in the module, references to the module-level variable must be appropriately qualified:

  1. An identifier declared at module-level conflicts with a procedure name.

For example, this error occurs if the variable MyID is declared at module level, and then a procedure is defined with the same name:

Having had this issue many times, and not fully understanding why, I think there is an important fact that I have tested, and someone can confirm. It may be obvious to professional programmers, but I place this here for those that seek these answers on discussions, who are usually not professional programmers.

A variable declared within a sub() is not «declared» (memory assigned) until that sub() is executed. And when the execution of that sub() is complete, the memory is released. Until now, I thought Public variables acted in similar way; available to any module that used it, —BUT only existing as long as the module where they were declared was still executing.

However, for any Public variable who’s declaration line is in any module in the workbook, that variable is declared and available at the execution of any module within the workbook, even if the module where the Public declaration exists is never called or executed.

Therefore, if you have a Public variable declaration in one module, and then again in a separate module that you plan to run independent of the first, Excel still sees 2 declarations for the same variable, and thus it is ambiguous.

To prove it, you can create a blank module within a workbook project, and add absolutely nothing except two Public declaration lines,

Public VariableX as String

Public VariableY as Integer

and those variables will be declared and available throughout the project, for any sub() executed. This fact is also probably the reason for the tip about minimizing the use of public variables.

Again, this may have been kindergarten level information for professional programmers, but most on this are not pros, and have to learn these lessons the hard way, or through discussion boards like this. I hope this helps someone.

Обнаружено неоднозначное имя

Идентификатор конфликтует с другим идентификатором или требует квалификации. Эта ошибка имеет следующие причины и способы решения:

Элементы с одинаковыми именами могут принадлежать нескольким объектам в одной и той же области видимости.

Квалифицируйте имя элемента, указывая имя объекта и точку. Пример:

Идентификаторы уровня модуля и идентификаторы уровня проекта (имена модуля и имена связанных проектов) могут повторно использоваться в процедуре, хотя это усложняет сопровождение и отладку программы. Но, если нужно сослаться в одной процедуре на оба элемента, необходимо квалифицировать элемент с более широкой областью видимости. Например, если переменная MyID объявлена на уровне модуля MyModule , а затем в модуле на уровне процедуры объявлена переменная с тем же именем, ссылки на переменную уровня модуля должны быть соответствующим образом квалифицированы:

Идентификатор, объявленный на уровне модуля, конфликтует с именем процедуры. Например, эта ошибка возникает, если переменная MyID объявлена на уровне модуля, а затем определена процедура с таким же именем:

В этом случае необходимо изменить можно из имен, так как квалификация с общим именем модуля не разрешит неоднозначность. Имена процедур по умолчанию являются общедоступными (Public), а имена переменных — частными (Private), если они не объявлены как Public.

Для получения дополнительной информации выберите необходимый элемент и нажмите клавишу F1 (для Windows) или HELP (для Macintosh).

Поддержка и обратная связь

Есть вопросы или отзывы, касающиеся Office VBA или этой статьи? Руководство по другим способам получения поддержки и отправки отзывов см. в статье Поддержка Office VBA и обратная связь.

Добавить комментарий

Ваш адрес email не будет опубликован.