Ошибка макроса cant find project or library

Хитрости »

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


Представим себе ситуацию — вы написали макрос и кому-то выслали. Макрос хороший, нужный, а главное — рабочий. Вы сами проверили и перепроверили. Но тут вам сообщают — Макрос не работает. Выдает ошибку — 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
ссылки
статистика

Сообщение будет показано после одобрения модератором.

 

lex

Пользователь

Сообщений: 71
Регистрация: 01.01.1970

Доброй ночи! Нужна помощь мудрецов.    
На листе «Список» если кликнуть по названию организации открывается заполненная форма. Есть кнопка «Создать клиента».  
На моем компе, где создавался и обкатывался файл все работает нормально. На любом другом при попытке открыть заполненную форму выскакивает ошибка «Can’t find project or library», открывается мой VBA проект с указанием места ошибки в тексте — это запись «[A2]» во второй строке текста в коде листа «Список».
Если это место исправляю, ошибка переползает далее по тексту. И так до бесконечности, до конца проекта. Но работать в итоге все равно отказывается. Пробовал на разных машинах, с различным офисом и ОС.  
У меня XP sp3, Office 2007 с кучей автоматически установленных обновлений от Microsoft. Кстати на ряде других компов стоял тот же софт.  
В чем может быть дело? Каких библиотек может не хватать?  
Заранее спасибо!

 

Alt-F11 / меню Tools / References / снять флажок с Ref Edit Control

 

lex

Пользователь

Сообщений: 71
Регистрация: 01.01.1970

Спасибо! Заработало! А в чем прикол этого флажка? И почему работало только на одном компе?

 

lex

Пользователь

Сообщений: 71
Регистрация: 01.01.1970

 

seergy

Пользователь

Сообщений: 64
Регистрация: 01.01.1970

#5

29.07.2009 08:09:17

так и не понял чем это лечить програмно. Например, если проект защищён и переходит от одного компа к другому…    
Использую следующие варианты.  
1) использовать позднее связывание с др. приложениями…    
2) Отключить все не используемые библиотеки… перед сохранением файла. Сделать фаг или надстройку для подключения нужных библиотек с контролами и др. предложениями..  
3) прикладывать сист. файлы .olb, .dll и др. либо указывать какой сервиспак поставить и прочие ситемные заплатки…  
Вопрос так есть ли универсальный метод лечить эту ошибку програмно.  
С увадением….

Сообщение будет показано после одобрения модератором.

0 / 0 / 0

Регистрация: 19.01.2016

Сообщений: 2

1

27.09.2016, 18:56. Показов 41536. Ответов 5


Студворк — интернет-сервис помощи студентам

Здравствуйте, у меня есть файл ексель с макросами, раньше все работало нормально, сейчас открываю и выдает ошибку «Microsoft Visual Basic for Applications» «Сan’t find project or library», далее нажимаю «ок» и Excell закрывается.

Читал другие темы, предлагают зайти в VBA — Refences и снять галочки с библиотек MISSING, но не могу, так как не могу открыть файл

Раньше на этом же компе этот файл работал без проблем

Поможете?

Спасибо!



0



Shersh

Заблокирован

27.09.2016, 19:23

2

Лучший ответ Сообщение было отмечено plyacik как решение

Решение

Открывайте файл с нажатым [Shift]`ом.
О результатах (хотя бы отрицательных) отпишитесь — будем думать дальше.



1



1342 / 312 / 76

Регистрация: 13.11.2008

Сообщений: 644

27.09.2016, 21:02

3

Цитата
Сообщение от plyacik
Посмотреть сообщение

далее нажимаю «ок»

А нажать Debug или End позволяет? Если да — то жмите End. Файл должен открыться, код остановиться. И тогда уже сможете перейти в код.
Либо же откройте Excel, перейдите в параметры и отключите макросы(отключить все макросы без уведомления). Закройте Excel и откройте свой файл. Он запустится без запуска макросов. Уберете все MISSING в References, сохраните файл. Теперь можно включать в параметрах макросы и перезапускать Excel.



1



0 / 0 / 0

Регистрация: 19.01.2016

Сообщений: 2

28.09.2016, 11:32

 [ТС]

4

В общем проблема решилась, но не очень разумным способом, нашел комп на котором открылся файл, пересохранил и все решилось.

кстати с нажатим Shift’ом тоже получилось, выскочило окно на котором отключил макросы, файл пересохранил и все ок

Спасибо!



0



0 / 0 / 0

Регистрация: 25.02.2020

Сообщений: 3

15.08.2020, 22:07

5

Случилась у меня такая же проблема, и есть там еще один обход.
Вот на этом видео — все рассказано, буквально пара минут: https://www.youtube.com/watch?… e=youtu.be



0



0 / 0 / 0

Регистрация: 03.07.2020

Сообщений: 169

20.04.2021, 11:59

6

Franky101010, не работает решение по указанной ссылке.
При нажатии на кнопку compile — просто ту же самую ошибку выдает.



0



Хитрости »

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


Представим себе ситуацию — вы написали макрос и кому-то выслали. Макрос хороший, нужный, а главное — рабочий. Вы сами проверили и перепроверили. Но тут вам сообщают — Макрос не работает. Выдает ошибку — 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
ссылки
статистика

So I’m having to run someone else’s excel app on my PC, and I’m getting «Can’t find Project or Library» on standard functions such as date, format, hex, mid, etc.

Some research indicates that if I prefix these functions with «VBA.» as in «VBA.Date» then it’ll work fine.

Webpages suggest it has to do with my project references on my system, whereas they must be ok on the developer’s system. I’m going to be dealing with this for some time from others, and will be distributing these applications to many others, so I need to understand what’s wrong with my excel setup that I need to fix, or what needs to be changed in the xls file so that it’ll run on a variety of systems. I’d like to avoid making everyone use «VBA.» as an explicit reference, but if there’s no ideal solution I suppose that’s what we’ll have to do.

  • How do I make «VBA.» implicit in my project properties/references/etc?

-Adam

Vincent's user avatar

Vincent

4273 silver badges11 bronze badges

asked Feb 3, 2009 at 14:05

Adam Davis's user avatar

Adam DavisAdam Davis

91.1k58 gold badges262 silver badges330 bronze badges

5

I have seen errors on standard functions if there was a reference to a totally different library missing.

In the VBA editor launch the Compile command from the menu and then check the References dialog to see if there is anything missing and if so try to add these libraries.

In general it seems to be good practice to compile the complete VBA code and then saving the document before distribution.

answered Feb 3, 2009 at 14:24

Dirk Vollmar's user avatar

Dirk VollmarDirk Vollmar

170k53 gold badges254 silver badges312 bronze badges

5

I had the same problem. This worked for me:

  • In VB go to Tools » References
  • Uncheck the library «Crystal Analysis Common Controls 1.0». Or any library.
  • Just leave these 5 references:
    1. Visual Basic For Applications (This is the library that defines the VBA language.)
    2. Microsoft Excel Object Library (This defines all of the elements of Excel.)
    3. OLE Automation (This specifies the types for linking and embedding documents and for automation of other applications and the «plumbing» of the COM system that Excel uses to communicate with the outside world.)
    4. Microsoft Office (This defines things that are common to all Office programs such as Command Bars and Command Bar controls.)
    5. Microsoft Forms 2.0 This is required if you are using a User Form. This library defines things like the user form and the controls that you can place on a form.
  • Then Save.

JimmyPena's user avatar

JimmyPena

8,6786 gold badges43 silver badges64 bronze badges

answered Jul 8, 2011 at 14:18

andres's user avatar

3

I have experienced this exact problem and found, on the users machine, one of the libraries I depended on was marked as «MISSING» in the references dialog. In that case it was some office font library that was available in my version of Office 2007, but not on the client desktop.

The error you get is a complete red herring (as pointed out by divo).

Fortunately I wasn’t using anything from the library, so I was able to remove it from the XLA references entirely. I guess, an extension of divo’ suggested best practice would be for testing to check the XLA on all the target Office versions (not a bad idea in any case).

answered Mar 4, 2009 at 22:44

RedBlueThing's user avatar

RedBlueThingRedBlueThing

41.6k17 gold badges97 silver badges122 bronze badges

In my case, it was that the function was AMBIGUOUS as it was defined in the VBA library (present in my references), and also in the Microsoft Office Object Library (also present). I removed the Microsoft Office Object Library, and voila! No need to use the VBA. prefix.

answered Jul 11, 2009 at 14:14

blue_wardrobeblue_wardrobe

In my case, I could not even open «References» in the Visual Basic window. I even tried reinstalling Office 365 and that didn’t work. Finally, I tried disabling macros in the «Trust Center» settings. When I restarted Excel, I got the warning message that macros were disabled, and when I clicked on «enable» I no longer got the error message.

Later I re-enabled all macros in the «Trust Center» settings, and the error message didn’t show up!

Hey, if nothing else works for you, try the above; it worked for me! :)

Update:
The issue returned, and this is how I «fixed» it the second time:

I opened my workbook in Excel online (Office 365, in the browser, which doesn’t support macros anyway), saved it with a new file name (still using .xlsm file extension), and reopened in the desktop software. It worked.

answered Feb 5, 2020 at 1:09

Sean McCarthy's user avatar

Sean McCarthySean McCarthy

4,4548 gold badges36 silver badges52 bronze badges

2

Even when all references are fine the prefix problem causes compile errors.

What about creating a find and replace sub for all ‘built-in VBA functions’ in all modules,
like this:

replace text in code module

e.g. «= Date» will be replaced with «= VBA.Date».

e.g. » Date(» will be replaced with » VBA.Date(» .

(excluding «dim t As Date» or «mydate»)

All vba functions for find and replace are written here :

vba functions list

answered Dec 4, 2020 at 22:30

Noam Brand's user avatar

Noam BrandNoam Brand

3052 silver badges12 bronze badges

For those of you who haven’t found any of the other answers work for you.

Try this:

Close out of the file, email it to yourself or if you’re at work, paste it from the network drive to your desktop, anything to get it to open in «protected mode».

Now open the file

DON’T CLICK ANY ENABLE EDITING OR THE YELLOW RIBBON

Go to the VBA Editor

Go to Debug — — Compile VBA Project, if «Compile VBA Project» is greyed out, then you may need to click the yellow ribbon one time to enable the content, but DO NOT enable macros.

After you click Compile, save, close out of the file. Reopen it, enable everything and it should be OK. This has worked for me 100% of the time.

answered Nov 3, 2021 at 19:27

Aspiring Developer's user avatar

In my case I was checking work done on my office computer (with Visio installed) at home (no Visio). Even though VBA appeared to be getting hung up on simple default functions, the problem was that I had references to the Visio libraries still active.

answered Feb 5, 2018 at 10:47

SmrtGrunt's user avatar

SmrtGruntSmrtGrunt

84913 silver badges24 bronze badges

I found references to an AVAYA/CMS programme file? Totally random, this was in MS Access, nothing to do with AVAYA. I do have AVAYA on my PC, and others don’t, so this explains why it worked on my machine and not others — but not how Access got linked to AVAYA. Anyway — I just unchecked the reference and that seems to have fixed the problem

answered Oct 9, 2019 at 8:10

Daniel Baker's user avatar

I’ve had this error on and off for around two years in a several XLSM files (which is most annoying as when it occurs there is nothing wrong with the file! — I suspect orphaned Excel processes are part of the problem)

The most efficient solution I had found has been to use Python with oletools
https://github.com/decalage2/oletools/wiki/Install and extract the VBA code all the modules and save in a text file.

Then I simply rename the file to zip file (backup just in case!), open up this zip file and delete the xl/vbaProject.bin file. Rename back to XLSX and should be good to go.

Copy in the saved VBA code (which will need cleaning of line breaks, comments and other stuff. Will also need to add in missing libraries.

This has saved me when other methods haven’t.

YMMV.

answered Sep 21, 2020 at 7:50

Sam's user avatar

So I’m having to run someone else’s excel app on my PC, and I’m getting «Can’t find Project or Library» on standard functions such as date, format, hex, mid, etc.

Some research indicates that if I prefix these functions with «VBA.» as in «VBA.Date» then it’ll work fine.

Webpages suggest it has to do with my project references on my system, whereas they must be ok on the developer’s system. I’m going to be dealing with this for some time from others, and will be distributing these applications to many others, so I need to understand what’s wrong with my excel setup that I need to fix, or what needs to be changed in the xls file so that it’ll run on a variety of systems. I’d like to avoid making everyone use «VBA.» as an explicit reference, but if there’s no ideal solution I suppose that’s what we’ll have to do.

  • How do I make «VBA.» implicit in my project properties/references/etc?

-Adam

Vincent's user avatar

Vincent

4273 silver badges11 bronze badges

asked Feb 3, 2009 at 14:05

Adam Davis's user avatar

Adam DavisAdam Davis

91.1k58 gold badges262 silver badges330 bronze badges

5

I have seen errors on standard functions if there was a reference to a totally different library missing.

In the VBA editor launch the Compile command from the menu and then check the References dialog to see if there is anything missing and if so try to add these libraries.

In general it seems to be good practice to compile the complete VBA code and then saving the document before distribution.

answered Feb 3, 2009 at 14:24

Dirk Vollmar's user avatar

Dirk VollmarDirk Vollmar

170k53 gold badges254 silver badges312 bronze badges

5

I had the same problem. This worked for me:

  • In VB go to Tools » References
  • Uncheck the library «Crystal Analysis Common Controls 1.0». Or any library.
  • Just leave these 5 references:
    1. Visual Basic For Applications (This is the library that defines the VBA language.)
    2. Microsoft Excel Object Library (This defines all of the elements of Excel.)
    3. OLE Automation (This specifies the types for linking and embedding documents and for automation of other applications and the «plumbing» of the COM system that Excel uses to communicate with the outside world.)
    4. Microsoft Office (This defines things that are common to all Office programs such as Command Bars and Command Bar controls.)
    5. Microsoft Forms 2.0 This is required if you are using a User Form. This library defines things like the user form and the controls that you can place on a form.
  • Then Save.

JimmyPena's user avatar

JimmyPena

8,6786 gold badges43 silver badges64 bronze badges

answered Jul 8, 2011 at 14:18

andres's user avatar

3

I have experienced this exact problem and found, on the users machine, one of the libraries I depended on was marked as «MISSING» in the references dialog. In that case it was some office font library that was available in my version of Office 2007, but not on the client desktop.

The error you get is a complete red herring (as pointed out by divo).

Fortunately I wasn’t using anything from the library, so I was able to remove it from the XLA references entirely. I guess, an extension of divo’ suggested best practice would be for testing to check the XLA on all the target Office versions (not a bad idea in any case).

answered Mar 4, 2009 at 22:44

RedBlueThing's user avatar

RedBlueThingRedBlueThing

41.6k17 gold badges97 silver badges122 bronze badges

In my case, it was that the function was AMBIGUOUS as it was defined in the VBA library (present in my references), and also in the Microsoft Office Object Library (also present). I removed the Microsoft Office Object Library, and voila! No need to use the VBA. prefix.

answered Jul 11, 2009 at 14:14

blue_wardrobeblue_wardrobe

In my case, I could not even open «References» in the Visual Basic window. I even tried reinstalling Office 365 and that didn’t work. Finally, I tried disabling macros in the «Trust Center» settings. When I restarted Excel, I got the warning message that macros were disabled, and when I clicked on «enable» I no longer got the error message.

Later I re-enabled all macros in the «Trust Center» settings, and the error message didn’t show up!

Hey, if nothing else works for you, try the above; it worked for me! :)

Update:
The issue returned, and this is how I «fixed» it the second time:

I opened my workbook in Excel online (Office 365, in the browser, which doesn’t support macros anyway), saved it with a new file name (still using .xlsm file extension), and reopened in the desktop software. It worked.

answered Feb 5, 2020 at 1:09

Sean McCarthy's user avatar

Sean McCarthySean McCarthy

4,4548 gold badges36 silver badges52 bronze badges

2

Even when all references are fine the prefix problem causes compile errors.

What about creating a find and replace sub for all ‘built-in VBA functions’ in all modules,
like this:

replace text in code module

e.g. «= Date» will be replaced with «= VBA.Date».

e.g. » Date(» will be replaced with » VBA.Date(» .

(excluding «dim t As Date» or «mydate»)

All vba functions for find and replace are written here :

vba functions list

answered Dec 4, 2020 at 22:30

Noam Brand's user avatar

Noam BrandNoam Brand

3052 silver badges12 bronze badges

For those of you who haven’t found any of the other answers work for you.

Try this:

Close out of the file, email it to yourself or if you’re at work, paste it from the network drive to your desktop, anything to get it to open in «protected mode».

Now open the file

DON’T CLICK ANY ENABLE EDITING OR THE YELLOW RIBBON

Go to the VBA Editor

Go to Debug — — Compile VBA Project, if «Compile VBA Project» is greyed out, then you may need to click the yellow ribbon one time to enable the content, but DO NOT enable macros.

After you click Compile, save, close out of the file. Reopen it, enable everything and it should be OK. This has worked for me 100% of the time.

answered Nov 3, 2021 at 19:27

Aspiring Developer's user avatar

In my case I was checking work done on my office computer (with Visio installed) at home (no Visio). Even though VBA appeared to be getting hung up on simple default functions, the problem was that I had references to the Visio libraries still active.

answered Feb 5, 2018 at 10:47

SmrtGrunt's user avatar

SmrtGruntSmrtGrunt

84913 silver badges24 bronze badges

I found references to an AVAYA/CMS programme file? Totally random, this was in MS Access, nothing to do with AVAYA. I do have AVAYA on my PC, and others don’t, so this explains why it worked on my machine and not others — but not how Access got linked to AVAYA. Anyway — I just unchecked the reference and that seems to have fixed the problem

answered Oct 9, 2019 at 8:10

Daniel Baker's user avatar

I’ve had this error on and off for around two years in a several XLSM files (which is most annoying as when it occurs there is nothing wrong with the file! — I suspect orphaned Excel processes are part of the problem)

The most efficient solution I had found has been to use Python with oletools
https://github.com/decalage2/oletools/wiki/Install and extract the VBA code all the modules and save in a text file.

Then I simply rename the file to zip file (backup just in case!), open up this zip file and delete the xl/vbaProject.bin file. Rename back to XLSX and should be good to go.

Copy in the saved VBA code (which will need cleaning of line breaks, comments and other stuff. Will also need to add in missing libraries.

This has saved me when other methods haven’t.

YMMV.

answered Sep 21, 2020 at 7:50

Sam's user avatar

Сообщение будет показано после одобрения модератором.

 

lex

Пользователь

Сообщений: 71
Регистрация: 01.01.1970

Доброй ночи! Нужна помощь мудрецов.    
На листе «Список» если кликнуть по названию организации открывается заполненная форма. Есть кнопка «Создать клиента».  
На моем компе, где создавался и обкатывался файл все работает нормально. На любом другом при попытке открыть заполненную форму выскакивает ошибка «Can’t find project or library», открывается мой VBA проект с указанием места ошибки в тексте — это запись «[A2]» во второй строке текста в коде листа «Список».
Если это место исправляю, ошибка переползает далее по тексту. И так до бесконечности, до конца проекта. Но работать в итоге все равно отказывается. Пробовал на разных машинах, с различным офисом и ОС.  
У меня XP sp3, Office 2007 с кучей автоматически установленных обновлений от Microsoft. Кстати на ряде других компов стоял тот же софт.  
В чем может быть дело? Каких библиотек может не хватать?  
Заранее спасибо!

 

Alt-F11 / меню Tools / References / снять флажок с Ref Edit Control

 

lex

Пользователь

Сообщений: 71
Регистрация: 01.01.1970

Спасибо! Заработало! А в чем прикол этого флажка? И почему работало только на одном компе?

 

lex

Пользователь

Сообщений: 71
Регистрация: 01.01.1970

 

seergy

Пользователь

Сообщений: 64
Регистрация: 01.01.1970

#5

29.07.2009 08:09:17

так и не понял чем это лечить програмно. Например, если проект защищён и переходит от одного компа к другому…    
Использую следующие варианты.  
1) использовать позднее связывание с др. приложениями…    
2) Отключить все не используемые библиотеки… перед сохранением файла. Сделать фаг или надстройку для подключения нужных библиотек с контролами и др. предложениями..  
3) прикладывать сист. файлы .olb, .dll и др. либо указывать какой сервиспак поставить и прочие ситемные заплатки…  
Вопрос так есть ли универсальный метод лечить эту ошибку програмно.  
С увадением….

Сообщение будет показано после одобрения модератором.

for some reason in my VBA code in excel, when it gets to a line of code where i am using mid it says can’t find project or library. what does this mean?

Oorang's user avatar

Oorang

6,5801 gold badge34 silver badges52 bronze badges

asked Dec 17, 2009 at 17:59

Alex Gordon's user avatar

Alex GordonAlex Gordon

54.9k283 gold badges662 silver badges1047 bronze badges

1

This is due some problem with references within VBA in your workbook.

In the VBA editor, go to ‘Tools-> References’. There you would find a reference with ‘MISSING:’ in front. Uncheck that and your problem should be fixed.

If the missing reference was something like ‘Visual Basic for Application’ or ‘Microsoft Office Object library, you should look for a reference that has no ‘MISSING:’ text and select this.

answered Dec 17, 2009 at 18:08

Dominik Fretz's user avatar

2

Go to the VBA editor (e.g. by using ALT-F11).

Click on Tools->References

If any references are marked MISSING then correct those missing references. This should fix your problem.

answered Dec 17, 2009 at 18:07

hawbsl's user avatar

hawbslhawbsl

15k24 gold badges73 silver badges113 bronze badges

2

Do you have any references to any library that is missing?

I’ve found that any bad reference — even when not used in the code — can throw the entire system off, so that even built-in functions are mapped wrong.

answered Dec 17, 2009 at 18:04

Michael Paulukonis's user avatar

I would go old skool and remove the structure manager activex control.

I gave similar instructions on how to do this are here!

Have a look at: regsvr32

  1. Close Excel
  2. Click Start / Run / cmd
  3. Type regsvr32 /u [path of old dll]/[filename]

Eg:
regsvr32 /u c:windowssystem32file.dll

(You can add /q to hide all messages)

Good luck!

Community's user avatar

answered Dec 18, 2009 at 2:48

Christian Payne's user avatar

Christian PayneChristian Payne

7,0425 gold badges38 silver badges59 bronze badges

«Click on Tools->References
If any references are marked MISSING then correct those missing references. This should fix your problem.»

It solved my problem (Left function throwing error «can’t find project or library).

answered Sep 7, 2016 at 15:35

user310563's user avatar

  • Remove From My Forums
  • Вопрос

  • Есть древний (2006 г) xla с макросами, выполняющими некоторую полезную работу.

    Рабочее место сотрудника было обновлено (выдан новый ПК с Windows 7/Office 2010).

    При попытке установки данного дополнения вылетает ошибка «Can’t find project or library» с предложением активации необходимой библиотеки в окне References, после чего (в случае отказа) естественно «плагин» не грузится и макросы не работают…

    Человек, писавший данный макрос уже давно не работает, перебирать все несколько сотен библиотек ручками не хочется, подключать их все — значительно замедлить скорость запуска Excel и возможно его работу…

    Логика подсказывает, что в VBA сценариях макроса исп. некоторые ф-ции, требующие подгрузки отдельной библиотеки.

    Вопрос. Возможно ли как-то определить необходимую библиотеку по наименованиям ф-ций в сценариях? Их там не так много (во всяком случае намного меньше чем библиотек)…

Ответы

  • В итоге поборол сам (по L-Atl+F11 вызывается редактор VB, там в Tools -> Preferences ищем потерянные связи (напротив такой будет стоять MISSING!).

    В моем случае немного начудил MS — нужную библиотеку (с ф-циями MID и *TRIM) почему-то перенесли из функционала Excel в библиотеку, относящуюся к Access, который естественно не был установлен (т.к. на старом ПК его не было)…

    • Помечено в качестве ответа

      19 сентября 2012 г. 11:16

0 / 0 / 0

Регистрация: 19.01.2016

Сообщений: 2

1

27.09.2016, 18:56. Показов 40408. Ответов 5


Здравствуйте, у меня есть файл ексель с макросами, раньше все работало нормально, сейчас открываю и выдает ошибку «Microsoft Visual Basic for Applications» «Сan’t find project or library», далее нажимаю «ок» и Excell закрывается.

Читал другие темы, предлагают зайти в VBA — Refences и снять галочки с библиотек MISSING, но не могу, так как не могу открыть файл

Раньше на этом же компе этот файл работал без проблем

Поможете?

Спасибо!

__________________
Помощь в написании контрольных, курсовых и дипломных работ, диссертаций здесь

0

Shersh

Заблокирован

27.09.2016, 19:23

2

Лучший ответ Сообщение было отмечено plyacik как решение

Решение

Открывайте файл с нажатым [Shift]`ом.
О результатах (хотя бы отрицательных) отпишитесь — будем думать дальше.

1

1331 / 304 / 72

Регистрация: 13.11.2008

Сообщений: 632

27.09.2016, 21:02

3

Цитата
Сообщение от plyacik
Посмотреть сообщение

далее нажимаю «ок»

А нажать Debug или End позволяет? Если да — то жмите End. Файл должен открыться, код остановиться. И тогда уже сможете перейти в код.
Либо же откройте Excel, перейдите в параметры и отключите макросы(отключить все макросы без уведомления). Закройте Excel и откройте свой файл. Он запустится без запуска макросов. Уберете все MISSING в References, сохраните файл. Теперь можно включать в параметрах макросы и перезапускать Excel.

1

0 / 0 / 0

Регистрация: 19.01.2016

Сообщений: 2

28.09.2016, 11:32

 [ТС]

4

В общем проблема решилась, но не очень разумным способом, нашел комп на котором открылся файл, пересохранил и все решилось.

кстати с нажатим Shift’ом тоже получилось, выскочило окно на котором отключил макросы, файл пересохранил и все ок

Спасибо!

0

0 / 0 / 0

Регистрация: 25.02.2020

Сообщений: 3

15.08.2020, 22:07

5

Случилась у меня такая же проблема, и есть там еще один обход.
Вот на этом видео — все рассказано, буквально пара минут: https://www.youtube.com/watch?… e=youtu.be

0

0 / 0 / 0

Регистрация: 03.07.2020

Сообщений: 169

20.04.2021, 11:59

6

Franky101010, не работает решение по указанной ссылке.
При нажатии на кнопку compile — просто ту же самую ошибку выдает.

0

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.

So I’m having to run someone else’s excel app on my PC, and I’m getting «Can’t find Project or Library» on standard functions such as date, format, hex, mid, etc.

Some research indicates that if I prefix these functions with «VBA.» as in «VBA.Date» then it’ll work fine.

Webpages suggest it has to do with my project references on my system, whereas they must be ok on the developer’s system. I’m going to be dealing with this for some time from others, and will be distributing these applications to many others, so I need to understand what’s wrong with my excel setup that I need to fix, or what needs to be changed in the xls file so that it’ll run on a variety of systems. I’d like to avoid making everyone use «VBA.» as an explicit reference, but if there’s no ideal solution I suppose that’s what we’ll have to do.

  • How do I make «VBA.» implicit in my project properties/references/etc?

-Adam

Vincent's user avatar

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.

So I’m having to run someone else’s excel app on my PC, and I’m getting «Can’t find Project or Library» on standard functions such as date, format, hex, mid, etc.

Some research indicates that if I prefix these functions with «VBA.» as in «VBA.Date» then it’ll work fine.

Webpages suggest it has to do with my project references on my system, whereas they must be ok on the developer’s system. I’m going to be dealing with this for some time from others, and will be distributing these applications to many others, so I need to understand what’s wrong with my excel setup that I need to fix, or what needs to be changed in the xls file so that it’ll run on a variety of systems. I’d like to avoid making everyone use «VBA.» as an explicit reference, but if there’s no ideal solution I suppose that’s what we’ll have to do.

  • How do I make «VBA.» implicit in my project properties/references/etc?

-Adam

Vincent's user avatar

Vincent

4173 silver badges11 bronze badges

asked Feb 3, 2009 at 14:05

Adam Davis's user avatar

Adam DavisAdam Davis

91.6k60 gold badges262 silver badges330 bronze badges

5

I have seen errors on standard functions if there was a reference to a totally different library missing.

In the VBA editor launch the Compile command from the menu and then check the References dialog to see if there is anything missing and if so try to add these libraries.

In general it seems to be good practice to compile the complete VBA code and then saving the document before distribution.

answered Feb 3, 2009 at 14:24

Dirk Vollmar's user avatar

Dirk VollmarDirk Vollmar

172k53 gold badges255 silver badges315 bronze badges

5

I had the same problem. This worked for me:

  • In VB go to Tools » References
  • Uncheck the library «Crystal Analysis Common Controls 1.0». Or any library.
  • Just leave these 5 references:
    1. Visual Basic For Applications (This is the library that defines the VBA language.)
    2. Microsoft Excel Object Library (This defines all of the elements of Excel.)
    3. OLE Automation (This specifies the types for linking and embedding documents and for automation of other applications and the «plumbing» of the COM system that Excel uses to communicate with the outside world.)
    4. Microsoft Office (This defines things that are common to all Office programs such as Command Bars and Command Bar controls.)
    5. Microsoft Forms 2.0 This is required if you are using a User Form. This library defines things like the user form and the controls that you can place on a form.
  • Then Save.

JimmyPena's user avatar

JimmyPena

8,6966 gold badges43 silver badges64 bronze badges

answered Jul 8, 2011 at 14:18

andres's user avatar

3

I have experienced this exact problem and found, on the users machine, one of the libraries I depended on was marked as «MISSING» in the references dialog. In that case it was some office font library that was available in my version of Office 2007, but not on the client desktop.

The error you get is a complete red herring (as pointed out by divo).

Fortunately I wasn’t using anything from the library, so I was able to remove it from the XLA references entirely. I guess, an extension of divo’ suggested best practice would be for testing to check the XLA on all the target Office versions (not a bad idea in any case).

answered Mar 4, 2009 at 22:44

RedBlueThing's user avatar

RedBlueThingRedBlueThing

41.9k17 gold badges96 silver badges122 bronze badges

In my case, it was that the function was AMBIGUOUS as it was defined in the VBA library (present in my references), and also in the Microsoft Office Object Library (also present). I removed the Microsoft Office Object Library, and voila! No need to use the VBA. prefix.

answered Jul 11, 2009 at 14:14

blue_wardrobeblue_wardrobe

In my case, I could not even open «References» in the Visual Basic window. I even tried reinstalling Office 365 and that didn’t work. Finally, I tried disabling macros in the «Trust Center» settings. When I restarted Excel, I got the warning message that macros were disabled, and when I clicked on «enable» I no longer got the error message.

Later I re-enabled all macros in the «Trust Center» settings, and the error message didn’t show up!

Hey, if nothing else works for you, try the above; it worked for me! :)

Update:
The issue returned, and this is how I «fixed» it the second time:

I opened my workbook in Excel online (Office 365, in the browser, which doesn’t support macros anyway), saved it with a new file name (still using .xlsm file extension), and reopened in the desktop software. It worked.

answered Feb 5, 2020 at 1:09

Sean McCarthy's user avatar

Sean McCarthySean McCarthy

4,7708 gold badges38 silver badges56 bronze badges

2

Even when all references are fine the prefix problem causes compile errors.

What about creating a find and replace sub for all ‘built-in VBA functions’ in all modules,
like this:

replace text in code module

e.g. «= Date» will be replaced with «= VBA.Date».

e.g. » Date(» will be replaced with » VBA.Date(» .

(excluding «dim t As Date» or «mydate»)

All vba functions for find and replace are written here :

vba functions list

answered Dec 4, 2020 at 22:30

Noam Brand's user avatar

Noam BrandNoam Brand

3252 silver badges13 bronze badges

For those of you who haven’t found any of the other answers work for you.

Try this:

Close out of the file, email it to yourself or if you’re at work, paste it from the network drive to your desktop, anything to get it to open in «protected mode».

Now open the file

DON’T CLICK ANY ENABLE EDITING OR THE YELLOW RIBBON

Go to the VBA Editor

Go to Debug — — Compile VBA Project, if «Compile VBA Project» is greyed out, then you may need to click the yellow ribbon one time to enable the content, but DO NOT enable macros.

After you click Compile, save, close out of the file. Reopen it, enable everything and it should be OK. This has worked for me 100% of the time.

answered Nov 3, 2021 at 19:27

Aspiring Developer's user avatar

In my case I was checking work done on my office computer (with Visio installed) at home (no Visio). Even though VBA appeared to be getting hung up on simple default functions, the problem was that I had references to the Visio libraries still active.

answered Feb 5, 2018 at 10:47

SmrtGrunt's user avatar

SmrtGruntSmrtGrunt

85912 silver badges25 bronze badges

I found references to an AVAYA/CMS programme file? Totally random, this was in MS Access, nothing to do with AVAYA. I do have AVAYA on my PC, and others don’t, so this explains why it worked on my machine and not others — but not how Access got linked to AVAYA. Anyway — I just unchecked the reference and that seems to have fixed the problem

answered Oct 9, 2019 at 8:10

Daniel Baker's user avatar

I’ve had this error on and off for around two years in a several XLSM files (which is most annoying as when it occurs there is nothing wrong with the file! — I suspect orphaned Excel processes are part of the problem)

The most efficient solution I had found has been to use Python with oletools
https://github.com/decalage2/oletools/wiki/Install and extract the VBA code all the modules and save in a text file.

Then I simply rename the file to zip file (backup just in case!), open up this zip file and delete the xl/vbaProject.bin file. Rename back to XLSX and should be good to go.

Copy in the saved VBA code (which will need cleaning of line breaks, comments and other stuff. Will also need to add in missing libraries.

This has saved me when other methods haven’t.

YMMV.

answered Sep 21, 2020 at 7:50

Sam's user avatar

Понравилась статья? Поделить с друзьями:
  • Ошибка макроса 2950 в access
  • Ошибка майнкрафта не удалось проверить имя пользователя
  • Ошибка майнкрафта не могу зайти
  • Ошибка майнкрафта java lang nullpointerexception null
  • Ошибка майнкрафта bad video card driver