Vba compile error can t find project or library

Хитрости »

Хитрости »

1 Май 2011              175622 просмотров


Представим себе ситуацию — вы написали макрос и кому-то выслали. Макрос хороший, нужный, а главное — рабочий. Вы сами проверили и перепроверили. Но тут вам сообщают — Макрос не работает. Выдает ошибку — Can’t find project or library. Вы запускаете файл — нет ошибки. Перепроверяете все еще несколько раз — нет ошибки и все тут. Как ни пытаетесь, даже проделали все в точности как и другой пользователь — а ошибки нет. Однако у другого пользователя при тех же действиях ошибка не исчезает. Переустановили офис, но ошибка так и не исчезла — у вас работает, у них нет.
Или наоборот — Вы открыли чей-то чужой файл и при попытке выполнить код VBA выдает ошибку Can’t find project or library.
Почему появляется ошибка: как и любой программе, VBA нужно иметь свой набор библиотек и компонентов, посредством которых он взаимодействует с Excel(и не только). И в разных версиях Excel эти библиотеки и компоненты могут различаться. И когда вы делаете у себя программу, то VBA(или вы сами) ставит ссылку на какой-либо компонент либо библиотеку, которая может отсутствовать на другом компьютере. Вот тогда и появляется эта ошибка. Что же делать? Все очень просто:

  1. Открываем редактор VBA
  2. Идем в ToolsReferences
  3. Находим там все пункты, напротив которых красуется MISSING.

    Снимаем с них галочки
  4. Жмем Ок
  5. Сохраняем файл

Эти действия необходимо проделать, когда выполнение кода прервано и ни один код проекта не выполняется. Возможно, придется перезапустить Excel. Что самое печальное: все это надо проделать на том ПК, на котором данная ошибка возникла. Это не всегда удобно. А поэтому лично я рекомендовал бы не использовать сторонние библиотеки и раннее связывание, если это не вызвано необходимостью
Чуть больше узнать когда и как использовать раннее и позднее связывание можно из этой статьи: Как из Excel обратиться к другому приложению.
Всегда проверяйте ссылки в файлах перед отправкой получателю. Оставьте там лишь те ссылки, которые необходимы, либо которые присутствуют на всех версиях. Смело можно оставлять следующие(это касается именно VBA -Excel):

  • Visual Basic for application (эту ссылку отключить нельзя)
  • Microsoft Excel XX.0 Object Library (место X версия приложения — 12, 11 и т.д.). Эту ссылку нельзя отключить из Microsoft Excel
  • Microsoft Forms X.0 Object Library. Эта ссылка подключается как руками, так и автоматом при первом создании любой UserForm в проекте. Однако отключить её после подключения уже не получится
  • OLE Automation. Хотя она далеко не всегда нужна — не будет лишним, если оставить её подключенной. Т.к. она подключается автоматически при создании каждого файла, то некоторые «макрописцы» используют методы из этой библиотеки, даже не подозревая об этом, а потом не могут понять, почему код внезапно отказывается работать(причем ошибка может быть уже другой — вроде «Не найден объект либо метод»)

Может я перечислил не все — но эти точно имеют полную совместимость между разными версиями Excel.

Если все же по какой-то причине есть основания полагать, что в библиотеках могут появиться «битые» ссылки MISSING, можно автоматически найти «битые» ссылки на такие библиотеки и отключить их нехитрым макросом:

Sub Remove_MISSING()
    Dim oReferences As Object, oRef As Object
    Set oReferences = ThisWorkbook.VBProject.References
    For Each oRef In oReferences
        'проверяем, является ли эта библиотека сломанной - MISSING
        If (oRef.IsBroken) Then
            'если сломана - отключаем во избежание ошибок
            oReferences.Remove Reference:=oRef
        End If
    Next
End Sub

Но для работы этого макроса необходимо:

  1. проставить доверие к проекту VBA:
    Excel 2010-2019 — Файл -Параметры -Центр управления безопасностью-Параметры макросов-поставить галочку «Доверять доступ к объектной модели проектов VBA»
    Excel 2007 — Кнопка Офис-Параметры Excel-Центр управления безопасностью-Параметры макросов-поставить галочку «Доверять доступ к объектной модели проектов VBA»
    Excel 2003— Сервис — Параметры-вкладка Безопасность-Параметры макросов-Доверять доступ к Visual Basic Project
  2. проект VBA не должен быть защищен

И главное — всегда помните, что ошибка Can’t find project or library может появиться до запуска кода по их отключению(Remove_MISSING). Все зависит от того, что и как применяется в коде и в какой момент идет проверка на «битые» ссылки.

Так же Can’t find project or library возникает не только когда есть «битая» библиотека, но и если какая-либо библиотека, которая используется в коде, не подключена. Тогда не будет MISSING. И в таком случае будет необходимо определить в какую библиотеку входит константа, объект или свойство, которое выделяет редактор при выдаче ошибки, и подключить эту библиотеку.
Например, есть такой кусок кода:

Sub CreateWordDoc()
    Dim oWordApp As Word.Application
    Set oWordApp = New Word.Application
    oWordApp.Documents.Add

если библиотека Microsoft Excel XX.0 Object Library(вместо XX версия приложения — 11, 12, 16 и т.д.) не подключена, то будет подсвечена строка oWordApp As Word.Application. И конечно, надо будет подключить соответствующую библиотеку.
Если используются какие-либо методы из библиотеки и есть вероятность, что библиотека будет отключена — можно попробовать проверить её наличие кодом и либо выдать сообщение, либо подключить библиотеку(для этого надо будет либо знать её GUIDE, либо полный путь к ней на конечном ПК).
На примере стандартной библиотеки OLE Automation(файл библиотеки называется stdole2) приведу коды, которые помогут проверить наличие её среди подключенных и либо показать сообщение либо сразу подключить.
Выдать сообщение — нужно в случаях, если не уверены, что можно вносить подобные изменения в VBAProject(например, если он защищен паролем):

Sub CheckReference()
    Dim oReferences As Object, oRef As Object, bInst As Boolean
    Set oReferences = ThisWorkbook.VBProject.References
    'проверяем - подключена ли наша библиотека или нет
    For Each oRef In oReferences
        If LCase(oRef.Name) = "stdole" Then bInst = True
    Next
    'если не подключена - выводим сообщение
    If Not bInst Then
        MsgBox "Не установлена библиотека OLE Automation", vbCritical, "Error"
    End If
End Sub

Если уверены, что можно вносить изменения в VBAProject — то удобнее будет проверить наличие подключенной библиотеки «OLE Automation» и сразу подключить её, используя полный путь к ней(на большинстве ПК этот путь будет совпадать с тем, что в коде):

Sub CheckReferenceAndAdd()
    Dim oReferences As Object, oRef As Object, bInst As Boolean
    Set oReferences = ThisWorkbook.VBProject.References
    'проверяем - подключена ли наша библиотека или нет
    For Each oRef In oReferences
        Debug.Print oRef.Name
        If LCase(oRef.Name) = "stdole" Then bInst = True
    Next
    'если не подключена - подключаем, указав полный путь и имя библиотеки на ПК
    If Not bInst Then
        ThisWorkbook.VBProject.References.AddFromFile "C:WindowsSystem32stdole2.tlb"
    End If
End Sub

Сразу подкину ложку дегтя(предугадывая возможные вопросы): определить автоматически кодом какая именно библиотека не подключена невозможно. Ведь чтобы понять из какой библиотеки метод или свойство — надо откуда-то эту информацию взять. А она внутри той самой библиотеки…Замкнутый круг :)

Так же см.:
Что необходимо для внесения изменений в проект VBA(макросы) программно
Как защитить проект VBA паролем
Как программно снять пароль с VBA проекта?


Статья помогла? Поделись ссылкой с друзьями!

  Плейлист   Видеоуроки


Поиск по меткам



Access
apple watch
Multex
Power Query и Power BI
VBA управление кодами
Бесплатные надстройки
Дата и время
Записки
ИП
Надстройки
Печать
Политика Конфиденциальности
Почта
Программы
Работа с приложениями
Разработка приложений
Росстат
Тренинги и вебинары
Финансовые
Форматирование
Функции Excel
акции MulTEx
ссылки
статистика

title keywords f1_keywords ms.prod ms.assetid ms.date ms.localizationpriority

Can’t find project or library

vblr6.chm1011094

vblr6.chm1011094

office

078ae060-a90b-e992-2cfb-34ee6b003098

08/14/2019

high

You can’t run your code until all missing references are resolved.

This error has the following causes and solutions:

  • A referenced project could not be found, or a referenced object library corresponding to the language of the project could not be found.

    Unresolved references are prefixed with MISSING in the References dialog box. Select the missing reference to display the path and language of the missing project or library. Follow these steps to resolve the reference or references:

To resolve the references

  1. Display the References dialog box.

  2. Select the missing reference.

  3. Start the Object Browser.

  4. Use the Browse dialog box to find the missing reference.

  5. Click OK.

  6. Repeat the preceding steps until all missing references are resolved.

Once you find a missing item, the MISSING prefix is removed to indicate that the link is reestablished. If the file name of a referenced project has changed, a new reference is added, and the old reference must be removed.
To remove a reference that is no longer required, simply clear the check box next to the unnecessary reference. Note that the references to the Visual Basic object library and host-application object library can’t be removed.

Applications may support different language versions of their object libraries. To find out which language version is required, click the reference and check the language indicated at the bottom of the dialog box.
Object libraries may be standalone files with the extension .OLB or they can be integrated into a dynamic-link library (DLL) They can exist in different versions for each platform. Therefore, when projects are moved across platforms, for example, from Macintosh to Microsoft Windows, the correct language version of the referenced library for that platform must be available in the location specified in your host application documentation.

Object library file names are generally constructed as follows:

  • Windows (version 3.1 and earlier): Application Code + Language Code + [Version].OLB. For example: The object library for French Visual Basic for Applications, Version 2 was vafr2.olb. The French Microsoft Excel 5.0 object library was xlfr50.olb.

  • Macintosh: Application Name Language Code [Version] OLB. For example: The object library for French Visual Basic for Applications, Version 2 was VA FR 2 OLB. The French Microsoft Excel 5.0 object library was MS Excel FR 50 OLB.

If you can’t find a missing project or library on your system, contact the referencing project’s author. If the missing library is a Microsoft application object library, you can obtain it as follows:

  • If you have access to Microsoft electronic technical support services, refer to the technical support section of this Help file. Under electronic services, you’ll find instructions on how to use the appropriate service option.

  • If you don’t have access to Microsoft electronic technical support services, Microsoft object libraries are available upon request as an application note from Microsoft. Information on how to contact your local Microsoft product support organization is also available in the technical support section of this Help file.

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

[!includeAdd-ins note]

[!includeSupport and feedback]

  • Remove From My Forums
  • Question

  • Recently installed MSOffice 2010 Pro trial version and receive the following Macro error in Excel: compile error.  Can’t find project or library.  The Excel file was created with Office 2003 and runs okay with the Professional version of 2003,
    but not the SMBS Excel 2003.  I tried setting the macro security level to low in 2010, however, the macro still will not run. 

Answers

  • Hi,

    Most likely, the application has lost the reference to an object or type library resulting in the above error when using
    Barcode Macros & Native VBA Functions.
    The problem may be resolved as follows:

    1.      
    Open the database or application.

    2.      
    Open a module in Design view or press ALT+F11 to switch to the Visual Basic Editor.

    3.      
    On the Tools menu, click References.

    4.      
    Clear the check box for the type library or object library marked as «Missing:»

    An alternative to removing the reference is to restore the referenced file to the path specified in the References dialog box.

    If the referenced file is in a new location, clear the «Missing:» reference and create a new reference to the file in its new location.

    Microsoft has documented this issue:
    VBA Functions Break in Database with Missing References

    Regards,

    Harry Yuan

    • Proposed as answer by

      Thursday, October 14, 2010 8:41 AM

    • Marked as answer by
      sacjac
      Thursday, October 14, 2010 1:10 PM

Summary:

Does your Excel application frequently showing Compile error can’t find project or library? Looking for some quick fixes to resolve can’t find project or library Excel error?

Here in this article, I have listed down some best possible fixes to troubleshoot Excel Macro Compile error. So go through it…!

It is found that Compile error can’t find project or library or Can’t find project or library Excel 2016 is faced by the users while using the VBA (Visual Basic Applications) for the macros to perform some assigned task.

Excel Can't Find Project Or Library Error

Here follow the solution to fix Excel can’t find project or library, but before moving further know the common causes responsible for getting the error.

Why Excel Is Showing Can’t Find Project Or Library Error?

  • This error is usually caused by the user’s Excel program. The reason is that your program is referenced to such object or library which is missing. Due to which your Excel program is unable to find it. So the program is unable to use VB or Micro-based functions or buttons. This leads to an error message appearance.
  • Since there are standard libraries so missing a library sounds a bit of the least chance. Another reason for this, in that case, is that library miss-match occurs. For example, the user may have a library version of 2007 but the reference in the code may be looking for the 2010 version of that specific library. So the program fails to find the corresponding library thus issuing the compilation error.
  • Sometimes a library may be toggled on or toggled off which causes a missing link issue between the library and program code. Therefore the compilation error occurs.
  • Another reason for the error message is concerning the use of Microsoft XP which includes a reference to web service in the VBA project. When you run this project in MS Office 2003, same compilation error appears. The reason is the same i.e. object or type of library is missing (or not found).

How To Fix Excel Can’t Find Project or Library Error?

To fix Excel Can’t Find Project or Library error you have to search for the missing Excel VBA References and after that uncheck Excel references.

Method 1# Look For Missing Reference

Here are the fixes that you need to follow:

1. Open your Excel application and then press ALT and F11 keys on your keyboard.
2. On the opened VBA window go to the tools>References dialog box.
3. Choose the missing reference and then start your Object Browser.
4. Use the Browse dialog box to make a search for your missing reference.
5. Hit the OK button.

Repeat the preceding steps until all missing references are resolved.

Method 2# Disable Missing Type Or Object Library Option

Commonly, the application has lost the reference to an object or type library resulting in the above error while using barcode macro and native VBA Functions.

To fix the Macros Compile error, follow the steps:

  • Open the Microsoft Excel file that is giving you the error message.
  • Make sure the Excel sheet or Datasheet that has the buttons or functions in question is selected.
  • Simultaneously press the ALT and F11 keys on your keyboard to switch to the Visual Basic Editor in a new window (as seen below).
  • In the new Visual Basic Editor window, click on the Tools menu at the top of the screen, and then click.
  • A References dialogue box will display on the screen. A missing type or object library is indicated by “MISSING:” followed by the name of the missing type or object library (an example is MISSING: Microsoft Excel 10.0 Object Library, as seen below).
  • If there is a checkmark in the checkbox next to the missing type or object library, then un-check the checkbox.
  • Click OK > Exit the Visual Basic Editor.
  • Save the original Excel file.
  • Try using the buttons or functions in question that previously didn’t work and they should now work normally.

An alternative for removing the reference is to restore the referenced file to the path specified in the references dialog box. If the referenced file is in a new location, clear the “Missing: ”reference and create a new reference to the file in its new location.

Automatic Solution: MS Excel Repair Tool

The above-mentioned manual solution will most probably sort out the issues and mentioned errors from the Excel file. But for any other corruption or file damage most suitable option would be to make use of MS Excel Repair Tool.

This is is highly competent in restoring corrupt Excel files and also retrieves data from worksheets like cell comments, charts, other data, and worksheet properties. This is a professionally designed program that can easily repair .xls and .xlsx files.

* Free version of the product only previews recoverable data.

Steps to Utilize MS Excel Repair Tool:

Conclusion:

Hope doing this will help you to fix the error Can’t find project or library Excel 2016, but if not then make use of the automatic third-party tool, this will help you to solve the error.

I tried my best to provide ample information about vba can’t find project or library errors and fixes. However, if you are having any additional fixes or any query then please share them with us.

Good Luck…

Priyanka is an entrepreneur & content marketing expert. She writes tech blogs and has expertise in MS Office, Excel, and other tech subjects. Her distinctive art of presenting tech information in the easy-to-understand language is very impressive. When not writing, she loves unplanned travels.

Понравилась статья? Поделить с друзьями:
  • Vba access обработка ошибок
  • Vb6 on error resume next
  • Vb6 on error goto
  • Vb6 error accessing system registry
  • Vb net on error resume next