Error in loading dll in excel vba

0 / 0 / 0

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

Сообщений: 99

1

13.05.2015, 22:18. Показов 18025. Ответов 4


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

Прошу помощи! Есть (или был) длинный код, который с большим скрипом писал несколько недель. Сейчас открываю документ, а мне Excel выдает ошибку «Error in loading DLL», а лист, на котором было многобукв абсолютно пустой! Копию книги не делал. Есть шанс восстановить код????



0



6076 / 1320 / 195

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

Сообщений: 1,023

14.05.2015, 11:51

2

Здравствуйте, Artyom52,

Вам может помочь следующая последовательность действий:

  1. Сделайте резервную копию проблемного файла.
  2. Откройте файл и отключите макросы.
  3. Посмотрите в Tools-References, нет ли там битых ссылок на библиотеки (начинающихся со слова MISSING).
  4. Уберите флажки со всех битых ссылок на библиотеки, сохраните и закройте файл.
  5. Откройте файл снова. Можно продолжать работу.

Рекомендации взяты с одного англоязычного форума и переведены на русский.

Еще там есть ряд полезных замечаний по поводу вышеприведенных рекомендаций:

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

С уважением,

Аксима



2



0 / 0 / 0

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

Сообщений: 99

14.05.2015, 22:18

 [ТС]

3

Аксима, спасибо за ответ. Действительно оказалась проблема с несовместимостью библиотек. Компьютер с офисом 2007 отказывается открывать программу, сделанную в 2003 офисе. Отключение отсутствующих библиотек тоже не помогает. Утром на рабочем компьютере все открылось как ни в чем ни бывало.
Единственное, я не понял, какие библиотеки и откуда мне нужно забрать и поставить в комп с 2007 офисом, чтобы все работало и там.

Можно ли набор всех необходимых библиотек прикрутить к самому файлу эксель, чтобы он по умолчанию был совместим с любым компьютером?



0



6076 / 1320 / 195

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

Сообщений: 1,023

15.05.2015, 09:47

4

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

какие библиотеки

Те библиотеки, которые помечены как отсутствующие на проблемном компьютере.

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

откуда мне нужно забрать

На рабочем компьютере посмотрите поле Location в меню Tools->References.
Предположим, на домашнем компьютере отсутствует библиотека «Microsoft ActiveX Data Objects 6.1 Library», которой я часто пользуюсь.
Находим на рабочем компьютере одноименную библиотеку, смотрим в поле Location и выясняем, что необходим файл C:Program FilesCommon FilesSystemadomsado15.dll.

Внезапная ошибка Error in loading DLL

И так же для других отсутствующих библиотек.

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

Можно ли набор всех необходимых библиотек прикрутить к самому файлу эксель

Сомневаюсь. Файл Excel не является исполняемым файлом, его нельзя скомпилировать вместе с нужными библиотеками.



1



Модератор

9167 / 3405 / 853

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

Сообщений: 5,185

Записей в блоге: 78

15.05.2015, 17:01

5

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

Можно ли набор всех необходимых библиотек прикрутить к самому файлу эксель, чтобы он по умолчанию был совместим с любым компьютером?

Можно это сделать несколькими способами просто хранив бинарные данные в нужном виде. Например в Base64 или как внедренный объект, после распаковывать и использовать.



0



Contents

  • 1 Introduction
  • 2 The magic solution that works almost 50% of the time
  • 3 Excel is crashing before you can try the magic solution
  • 4 “Error in loading DLL” when referencing a TLB
  • 5 “Error in loading DLL” when compiling the VBA project
  • 6 The addin does not want to load
  • 7 NullReferenceException thrown by the .Net (C#, VB.Net…) addin code
  • 8 Generic run-time errors
  • 9 All other unknown mystic errors
  • 10 Conclusion

Introduction

So you have deployed your awesome Excel addin in production and all is working fine for some weeks : you are enjoying your success…
But one day the phone rings and the guy at the other side is not really happy; no, he is completely upset and you could almost smell his breath when he screams.
But why? Because your awesome addin has stopped working on his workstation without notice.

Sometimes the root-cause is obvious: you have delivered a new version, but in many cases you will hardly ever know the root-cause of this annoying situation: Windows update, Office update, quick and dirty moving/installation of the addin from a workstation to another one, bad alignment of Uranus and Jupiter…

A wealth of errors can happen, then it’s hard to have them all in mind, especially when you are in a hurry and with stress you start to get mixed up. So to be as efficient as possible you’d better have a checklist and this is precisely what this article will be, enumerating all the errors I have encountered describing usual causes and solutions.

So let’s troubleshoot!

The magic solution that works almost 50% of the time

If the error message does not inspire you or Excel crashes without notice when you call an external API from VBA (this often happens when you are using a third-party API that can evolve independently of the worksheets that use it) and you want or need to move fast you can try this as a first shot:

  1. go into the VBA editor (ALT-F11 is a handy shortcut)
  2. in the top menu choose “Tools” then “References” :

    VBA Tools References

    VBA Tools References

    you should see this popup :vba_references_popupThe reference can point to an XLA file or a TLB file (which is the interface of your addin used by VBA).

  3. locate your addin reference (if selected it should be at the top), uncheck it and click “OK
  4. reopen this popup, locate you addin (you can type its first letter to directly go to the first addin whose name starts with this letter) but this time recheck it
  5. restart the operation that was broken and cross your fingers, it may be OK now
  6. still sucks? follow the rest of this guide depending on your error

I’ve seen the unreference/rereference trick working for :

  • Error 430 “class does not support automation or does not support expected interface” :

    VBA Error 430

    VBA Error 430

    which is typically the consequence of an update of your addin API like changing the signature of a method.

  • Out of memory” errors :

    VBA Out of memory error

    VBA Out of memory error

  • VBA/addin interface mismatch: from VBA you call method “A” of your addin but you end up in method “B“. I’ve seen this happen a few times, at least when the two methods have the same signature and are close in the API, otherwise you should have an explicit error.
  • and a bunch of other situations…

If your Excel application is made of normal spreadsheets (XLS, XLSM…) and XLAs do not forget to update the references for all the files referencing your addin, not only the spreadsheets.

Excel is crashing before you can try the magic solution

Sometimes you’re really not in luck and while you feel that a simple “unreference/rereference” could do the job Excel does not give you the opportunity to try it as it crashes before you can access the VBA editor.

This issue can occur if the workbook is referencing the absolute path to the TLB on your development environment and you deploy the workbook as is in your production environment where the TLB will probably be in another place (typically a sub-directory of “Program Files”).
It can also occurs if you have multiple versions of your addin on the workstation.
It can often happens on your development workstation if:

  • you develop with multiple workspaces (one for each of your SVN/Git branches) and there is a mix between the different TLBs and addins : you can try a full cleanup (including Windows registry) and rebuild from the workspace you’re currently working on
  • you use a task manager or integration server like Jenkins (ex Hudson) which builds your addin and register it into the system in your back : you can temporarily disable the task that breaks your setup

If the workbook is broken in production, you can use two solutions :

  1. Start Excel in safe-mode, either by starting it from the “Run” popup (shortcut is Windows-R) with the “/safemode” option :

    Run Excel in safe-mode

    Run Excel in safe-mode

    or by pressing continuously the CTRL key while starting it which should trigger the following popup :

    Excel start safemode

    Excel start safemode

    Once Excel is started in safe-mode load the broken workbook. You should be able to access the “References” popup and do the unreference/rereference trick.

  2. You can temporarily move or rename the TLB file and starts your Excel application as usual. Excel should not crash anymore and starts as usual, only complaining about the missing TLB. You can now move/rename the TLB as it was before, proceed to the “unreference/rereference” trick and then save the workbook to ensure the correct reference is kept. All should be fine at the next startup.

“Error in loading DLL” when referencing a TLB

If, when referencing a TLB, you see this popup :

VBA Error in loading DLL

VBA Error in loading DLL

this is probably the sign that Excel cannot access the TLB file, the root cause can be :

  • a simple installation issue : the TLB not being where it is expected (you can check the expected path in the Windows registry using RegEdit); so check the correct installation of your application and reinstall it if necessary.
  • user rights issue with the TLB, and more generally all the installation items : this can happen if you have installed your application with a user that is not the one currently trying to use the application (e.g. a remote user).
    You can then either:

    • proceed to a dedicated reinstallation for the current user,
    • change the rights of the installation items to allow him full access,
    • or add him to a user-group that has the required rights,

    whichever you find easier and cleaner in your situation.

“Error in loading DLL” when compiling the VBA project

If this error occurs when the VBA code is compiled, either automatically when accessing a function/sub that uses the addin API or manually when clicking the Debug/Compile menu item then check if you have recently changed the settings of a dependency (e.g. of your .Net (C#, VB.Net…) project) that contains COM types you expose through your addin API.

I’ve seen this issue once in a C# project with the ADODB dll when the “Embed Interop Types” option was set to “True” in the reference properties. With only this settings and “Copy Local” to “False” a method of the addin that returned an ADODB connection was broken in Excel 2003 on Windows XP whereas all was working fine on Excel 2010 on Windows 7. I’ve not dived into the details but it seems the “Embed Interop Types” feature is not retro-compatible or may need some additional setup on the workstation, which in both case made it unusable.

So, setting “Embed Interop Types” to “False” and reverting “Copy Local” to “True” solved the issue caused by Visual Studio 2010 because it activates these settings by default with .Net 4.0 projects (the project had recently been migrated from .Net 3.5 to .Net 4.0)!

ADOBD Reference Properties

ADOBD Reference Properties

As often VS wanted to help but broke something 🙂

The addin does not want to load

If, depending on the way you load your addin, you have the following symptoms:

  • you use the Excel interface: you can see the addin in the “COM Addins” list and you can check it:

    COM addin checked

    COM addin checked

    but when you reopen the “COM Addins” popup your addin is not checked anymore.

  • you use VBA code: when you try to set the Connect property of the addin:
    Dim boomAddin As COMAddIn
    ...
    boomAddin.Connect = True
    

    you get a “Run-time error ‘287’: Application-defined or object-defined error“:

    VBA connect disabled addin error popup

    VBA connect disabled addin error popup

In both cases it’s the sign Excel cannot or does not want to load the addin.

This can happen if your addin throws an exception when loaded, ie in the “OnConnection” method; in this case you should see a warning at the bottom of your addin description, in the “Load Behavior” field:

Excel COM addin error

Excel COM addin error

You can reproduce this behavior with a simple code:

public void OnConnection(object application, Extensibility.ext_ConnectMode connectMode, object addInInst, ref System.Array custom)
{
    applicationObject = application;
    addInInstance = addInInst;

    throw new Exception("Boom!");
}

But if your addin causes more serious damages like an Excel crash, what you can experiment with such a code (note that the crash can happen in another method that OnConnection with the same sanction):

public void OnConnection(object application, Extensibility.ext_ConnectMode connectMode, object addInInst, ref System.Array custom)
{
    applicationObject = application;
    addInInstance = addInInst;

    System.Diagnostics.Process.GetCurrentProcess().Kill();
}

Excel won’t trust your addin anymore and may put in quarantine ALL the addins loaded at the time of the crash!
In this case, if you are lucky, at the next startup, Excel should warn you of the issue with this message:

Excel addin serious problem

Excel addin serious problem

You can choose to give your addin a second chance by answering “No” or you can answer “Yes” so the addin will stay disabled and you won’t be able to load it into Excel until you notify Excel the addin should not be kept in quarantine any longer.

But if you are in doubt and think your addin may have been disabled how to check ?
You have at least two solutions :

  •  using Excel 2010 : go to the “File” ribbon tab then “Options” :

    Excel2010 File Options

    Excel2010 File Options

    You should see the “Excel Options” popup in which you now select “Add-Ins” :

    Excel 2010 Options Add-Ins

    Excel 2010 Options Add-Ins

    From here scroll down to the bottom of the list where the disabled items are listed.
    Here is an example of a too zealous Excel that has disabled all the COM addins (and they were a lot!) :

    Excel2010 Disabled addins

    Excel2010 Disabled addins

    To show the culprit of all this mess use the “Manage” drop-down at the bottom of the window and choose “Disabled Items” :

    Excel 2010 Go To Disabled

    Excel 2010 Go To Disabled

    then click the “Go…” button to show the bad guy :

    Excel 2010 Culprit Addin

    Excel 2010 Culprit Addin

    If you forgive your addin then select it and click “Enable” then “Close” :

    Excel 2010 Addin Reenable

    Excel 2010 Addin Reenable

    You should now be able to reload it and all the other addins disabled due to the crash via the “COM Add-Ins” popup.

  • using the Windows registry : Excel stores the disabled items list into the registry under the keys “…SoftwareMicrosoftOffice14.0ExcelResiliencyDisabledItems“, e.g. “HKEY_CURRENT_USERSoftwareMicrosoftOffice14.0ExcelResiliencyDisabledItems“. If an addin has been disabled you’ll find a binary key holding its name :

    RegEdit DisabledItems Key

    RegEdit DisabledItems Key

    We can read the identity of our explosive addin : “boomaddin”.
    If you want to reenable it you can either:

    • delete the numerical entry (here “5793E01E”)
    • delete the whole “DisabledItems” key

    Note that this change will be effective only for the next Excel instances, so you’ll have to restart your application to be able to load your addin as usual.

NullReferenceException thrown by the .Net (C#, VB.Net…) addin code

Object reference not set to an instance of an object” like errors :

VBA Object reference error popup

VBA Object reference error popup

generally happen when your .Net addin has not been loaded by Excel, so initialization code has not been executed (typically the part that captures the Excel application instance loading the addin).
Therefore your addin code may be naively accessing not initialized references.

Indeed you’ll typically use code like this one :

public void OnConnection(object application, Extensibility.ext_ConnectMode connectMode, object addInInst, ref System.Array custom)
{
    // keep the application object for future use
    applicationObject = application;
    addInInstance = addInInst;

    // other initialization code
}

public void DoSomething()
{
    // oops! if the addin is not loaded this code will throw a NullReferenceException
    (applicationObject as Application).ActiveCell.Value2 = "Something";
}

If the addin is not loaded the “OnConnection” method will not be called, then the “applicationObject” reference will not be initialized with the running Excel instance.

It could also happen that something is broken inside the “OnConnection” method itself preventing it from running to its end, letting the addin half-initialized (which is far more dangerous than not initialized at all as the resulting errors and behavior will be more surprising and entertaining ;)).
So you should always keep track of your addin state and notify of any inconsistency : using a simple boolean flag set to “true” at the end of initialization (typically at the end of the “OnConnection” method) should be sufficient in most cases.

So refer to point 5) to check the status of your addin.

Generic run-time errors

Sometimes you get this kind of anonymous error popup :

Excel Automation error

Excel Automation error

To make sense of this cryptic and apparently useless message you should lookup your error-code/HRESULT (here 80131524) in this list.

In this case the error was COR_E_DLLNOTFOUND due to a missing native DLL used through DllImport by the C# addin (itself called by a VBA macro).

Deployment of native DLLs often causes issues that you can troubleshoot using Dependency Walker (see my article about it).

All other unknown mystic errors

If you have any error not referenced here, for which you don’t find a solution by googling it and whose root-cause is impenetrable then, in desperation, you can try to remove any trace of your addin in your system :

  • remove all the files and directories that contain the assets of your application like XLS/XLSX/XLSM spreadsheets (whose references could have been corrupted), DLLs and TLBs
  • cleanup the registry by hand by looking for all the references to your addin : DLLs and TLBs keys should be enough but you can also remove all the COM registration information of your types.

Then reinstall the addin and cross your fingers…

It should be relatively uncommon to need this : in the last year I’ve never had to go this far thanks to my better understanding of Excel addins and this kind of checklist.

Conclusion

If this article has helped you troubleshoot an issue I’d like to read your story.

If you have any remarks or suggestions about this article or if you know other errors with their standard fixes please share by letting a comment, I’ll do my best to update this article with your feedback.

I have an Excel tool I’ve been building at work to automatically generate PowerPoint charts from data on Excel sheets. I’ve been moving the project back and forth between my work and home computers.

At work I have Excel 2013 and at home I have Excel 2016. So when I move the file from home to work, I have to go into references and uncheck the «MISSING: Microsoft PowerPoint 16.0 Object Library» and check «Microsoft PowerPoint 15.0 Object Library»…no big deal.

Until this morning. When I open the VB Editor I get a messagebox

Error in loading DLL

I can’t open any of the forms of modules…I just get that messagebox.

When I go to references I’ve tried

  • Uncheck the missing entry for v16 and check the entry for version 15
    — I get the error in loading DLL message
  • Just unchecking the entry for v16 — I get the error in loading DLL
    message
  • Leaving them both checked — I (obviously) get the error message
    «Name conflicts with existing module, project, or object library»
  • Uncheck the missing entry, check the correct entry, and move its
    priority above the (unchecked) missing entry — I get the error in
    loading DLL message.

Вы выложили книгу с паролем на код VBA, но пароль не сообщили.
Согласно

п 3.9 Правил

здесь запрещено рассматривать вопросы, связанные со вскрытием паролей и защит.
Очевидно, расчёт был на очередное «чудо» без вскрытия защиты типа предыдущего, но такое случается не часто :)
Правильнее и надежнее все же связаться с разработчиком (Евгением Волковым) и заинтересовать его в оказании помощи.

Без вскрытия пароля совершенно точно можно утверждать, что:
1. На компьютерах с 64-битным Office 2010 код работать не будет, так как используется MSDASQL провайдер.
2. На компьютерах, где с Excel 2007 код работает, он будет работать и c Excel 2010 32-бит.

В связи с этим доп. инфо для Ваших IT-ников.
Если данные хранятся в базе данных на SQL Server, то используется такая связка:
Клиентское приложение (EXCEL.EXE) – Microsoft OLE DB Provider for ODBC Drivers (MSDASQL.DLL) – ODBC Driver Manager (ODBC32.DLL) – SQL Server ODBC Driver (SQLSRV32.DLL) – локальная сеть – SQL Server – база данных.
Данные могут храниться и локально, например, в DBF формате, Вам там виднее, и правильнее было бы это также сообщить.

Но, судя по ошибке, код не находит базу данных.
Скорее всего, это связано с тем, что на проблемных компьютерах источник данных не прописан в DSN-файле.
Можно попробовать поискать на работающем компьютере файл с именем EvalarSeven.dsn в папке:
C:Program FilesCommon FilesODBC
или в C:Program Files (x86)Common FilesODBC
или в скрытой папке: Мои документыМои источники данных
и скопировать его в аналогичную папку проблемного компьютера.

  • Remove From My Forums
  • Question

  • User210110650 posted
    Hi Experts, I am using VB 6.0 and in my app I involk Excel. My app has been working fine for quite some time. Recently I got a runtime error ’48’ — «Error in loading DLL» when I try to involk the Excel. The stange thing is the same app involks Excel fine on
    other PCs. I think it’s some MS Office set up problems, but after I uninstall MS Office XP and reinstall MS Office XP, the error still exists. Can any one know what is the cause of problem and how to fix it ? Thank you in advance.

Answers

  • User1006193418 posted

    Hi Experts, I am using VB 6.0 and in my app I involk Excel. My app has been working fine for quite some time. Recently I got a runtime error ’48’ — «Error in loading DLL» when I try to involk the Excel.

    The stange thing is the same app involks Excel fine on other PCs. I think it’s some MS Office set up problems, but after I uninstall MS Office XP and reinstall MS Office XP, the error still exists. Can any one know what is the cause of problem and how to
    fix it ? Thank you in advance.

    Hi hemantkamb,

    Is there any more information displayed with the error message? As I know, The error ‘Error in loading DLL’ is often caused with a bad installation or an issue caused after another program has been installed that replaced the programs DLL. If
    there is any message telling what DLL file is missing, that will be more helpful to handle this problem.

    Since you have already done this step with Microsoft Office XP, it seems that the error DLL file is not raleted to the Office. Then, please try to remember is there any new programes installed or uninstalled with you computer before the issue shows
    up, especially those system programs. If so, try to recover them.

    In addition, reinstalling Visual Basic Studio 6.0 is also a suggestion to this situation.

    Best Regards,
    Shengqing Yang

    • Marked as answer by

      Thursday, October 7, 2021 12:00 AM

  • User1006193418 posted

    Yesterday my application has given me error for to open project that the file
    mscomctl not loading.

    Hi hemantkamb,

    Then, try to seaching the key word mscomctl in ‘My Computer’ to find is there any problem with the file
    mscomctl.

    I have got a result as the screen shot below:

    You may have a differen result from mine, but whatever you get, compare them with those computer which could run the application well. If there is any problem with the version in your computer, try to copy the correct version from another computer and
    to run the application again.

    [Idea]IMPORTANT NOTE: before you replace the version in your computer, do make sure you have a backup of those files!

    Best Regards,
    Shengqing Yang

    • Marked as answer by
      Anonymous
      Thursday, October 7, 2021 12:00 AM

Понравилась статья? Поделить с друзьями:
  • Error in load dll excel
  • Error excel this workbook
  • Error driver odbc excel
  • Error checking for excel
  • Error 450 vba excel