Надстройка Excel не загружается при открытии Excel из VBA

Надстройка Excel не загружается при открытии Excel из VBA

Я использую Excelнадстройка reg-exи он работает хорошо, единственная проблема в том, что он не загружается, когда Excel запускается из VBA.

У меня есть макрос в Word для сбора некоторых данных в Word и копирования их в Excel. Он запускает Excel, вывод отличный, но мне нужно перезапустить Excel, чтобы использовать надстройку (она включена в параметрах, просто не загружается).

Я попробовал другой макрос: просто открыть Excel и создать новую книгу, и там та же проблема.

У меня есть только одна сторонняя надстройка, поэтому я не могу сравнивать ее с другими.

Есть идеи?

решение1

Вот как это должно работать.

Из документации COM.

      Component Automation  
Exposing the Application Object  

 Language Filter: All Language Filter: Multiple Language Filter: Visual Basic Language Filter: C# Language Filter: C++ Language Filter: J# Language Filter: JScript  
 Visual Basic (Declaration) 
 Visual Basic (Usage) 
 C# 
 C++ 
 J# 
 JScript 

Any document-based, user-interactive applications that expose ActiveX objects should have one top-level object named the Application object. This object is initialized as the active object when an application starts.

The Application object identifies the application and provides a way for ActiveX clients to bind to and navigate the application's exposed objects. All other exposed objects are subordinate to the Application object; it is the root-level object in the object hierarchy.

The names of the Application object's members are part of the global name space, so ActiveX clients do not need to qualify them. For example, if MyApplication is the name of the Application object, a Visual Basic program can refer to a method of MyApplication as MyApplication.MyMethod or simply MyMethod. However, you should be careful not to overload the Application object with too many members because it can cause ambiguity and decrease performance. A large, complicated application with many members should be organized hierarchically, with a few generalized objects at the top, branching out into smaller, more specialized objects. 

The following chart shows how applications should expose their Application and Document objects.

Command line  Multiple-document interface application  Single-document interface application  
/Embedding 
 Expose class factories for document classes, but not for the application.

Call RegisterActiveObject for the Application object.
 Expose class factories for document class, but not for the application.

Call RegisterActiveObject for the Application object.

/Automation 
 Expose class factories for document classes.

Expose class factory for the application using RegisterClassObject.

Call RegisterActiveObject for the Application object.
 Do not expose class factory for document class.

Expose class factory for the Application object using RegisterClassObject.

Call RegisterActiveObject for the Application object.

No OLE switches 
 Expose class factories for document classes, but not for the application.

Call RegisterActiveObject for the Application object.
 Call RegisterActiveObject for the Application object. 


The call to RegisterActiveObject enters the Application object in OLE's running object table (ROT), so ActiveX clients can retrieve the active object instead of creating a new instance. Visual Basic applications can use the GetObject statement to access an existing object.

 © Microsoft Corporation. All rights reserved. 

Таким образом, /a или /embedding не загрузит ничего, кроме голого приложения (и /a также является хорошим шагом для устранения неполадок).

Запустите приложение, а затем выполните в нем GetObject.

Также нет смысла использовать такой addin, поскольку вы можете делать то же самое, что делает addin. Это vbs (так что его можно вставить в VBA), использующий тот же движок RegEx, что и ваш addin (Word также имеет свой собственный движок RegEx, называемый Use Wildcards). Установите ссылку на Microsoft VBScript Regular Expression 5.5.

Set regEx1 = New RegExp
If Instr(LCase(Arg(1)), "i") > 0 then
    regEx1.IgnoreCase = True
Else
    regEx1.IgnoreCase = False
End If 
If Instr(LCase(Arg(1)), "v") > 0 then
    IncExc = False
Else
    IncExc = True
End If 
regEx1.Global = False
regEx1.Pattern = Pttn 
Do Until Inp.AtEndOfStream
    Line=Inp.readline
    If RegEx1.Test(Line) = IncExc then
        outp.writeline Line
    End If
Loop

решение2

Я решил эту проблему на основе ответа, опубликованного на аналогичный вопрос в stackoverflow:https://stackoverflow.com/a/806720/4721734

Я снова рассмотрел эту проблему, и коллекция Application.Addins, похоже, содержит все надстройки, перечисленные в меню Tools->Addins, с логическим значением, указывающим, установлена ​​ли надстройка. Так что то, что, похоже, работает для меня сейчас, это цикл по всем надстройкам, и если .Installed = true, то я устанавливаю .Installed в False и обратно в True, и это, похоже, правильно загружает мои надстройки.

Function ReloadXLAddins(TheXLApp As Excel.Application) As Boolean

    Dim CurrAddin As Excel.AddIn

    For Each CurrAddin In TheXLApp.AddIns
        If CurrAddin.Installed Then
            CurrAddin.Installed = False
            CurrAddin.Installed = True
        End If
    Next CurrAddin

End Function

Связанный контент