使用 VB.NET 为 VBA IDE 构建插件

发布于 2024-08-16 09:58:15 字数 72 浏览 2 评论 0原文

我在其他地方问过这个问题,但从未发现有人知道如何使用 VB.NET 为 VBA IDE 构建插件。有可能吗?有人能给我举个例子吗?

I have asked this elsewhere, but have never found anyone knows how to build an add-in for VBA IDE using VB.NET. Is it even possible? Could someone point me to an example?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(6

牛↙奶布丁 2024-08-23 09:58:15

您可能需要使用 IDTExtensibility2 接口编写 com 插件,从新项目中选择共享插件项目模板。

编辑

否则,要从头开始创建此插件,您将需要执行以下操作:

  1. 创建一个新的项目类库
  2. 添加对“扩展性”的引用,它应该在列表中。您可能需要下载适合您的 Office 版本的 PIA。 (也许还有 VSTO,但我对此不确定)
  3. 再次添加对“Microsoft.Vbe.Interop”的引用应该与 PIA 一起使用。
  4. 选中属性选项卡中的“Register for Com Interop”框。
  5. 可选在调试设置选项卡中,将启动更改为外部程序,并在programfiles文件夹中输入excel exe的路径(如果这是针对excel的),这是为了允许项目可调试。
  6. 可选 在命令选项中添加一个条目到工作表或 Word 文档,该条目将在启动时使用宏显示插件对话框,对于开发来说,这对于简化调试体验很有意义。例如“C:\vbe.xlsm”
  7. 可选 还要设置工作表目录的启动路径,例如“C:\”
  8. 实现“Extensibility”程序集中的接口“IDTExtensibility2”。
  9. 将此类命名为“Connect”(这只是一个首选项)
  10. 使用以下属性为该类添加属性

[ComVisible(true),
Guid("您生成的Guid"),
ProgId("YourAddinName.Connect")]

这是一个帮助您入门的实现,首先将“YourAddinName”替换为您的AppName,并为“YourGenerateGuid”创建一个Guid。
您需要将插件注册到正确的注册表位置,查看后面的注册表项以了解情况,还需要替换注册表项中的一些变量。

Imports System
Imports System.Drawing
Imports System.Linq
Imports System.Runtime.InteropServices
Imports Extensibility
Imports Microsoft.Vbe.Interop

Namespace VBEAddin


''' <summary>
''' The object for implementing an Add-in.
''' </summary>
''' <seealso class='IDTExtensibility2' />
<Guid("YourGeneratedGuid"), ProgId("YourAddinName.Connect")> _ 
Public Class Connect
    Implements IDTExtensibility2
    Private _application As VBE 'Interop VBE application object


    #Region "IDTExtensibility2 Members"

    ''' <summary>
    ''' Implements the OnConnection method of the IDTExtensibility2 interface.
    ''' Receives notification that the Add-in is being loaded.
    ''' </summary>
    ''' <param term='application'>
    ''' Root object of the host application.
    ''' </param>
    ''' <param term='connectMode'>
    ''' Describes how the Add-in is being loaded.
    ''' </param>
    ''' <param term='addInInst'>
    ''' Object representing this Add-in.
    ''' </param>
    ''' <seealso class='IDTExtensibility2' />
    Public Sub OnConnection(ByVal application As Object, ByVal connectMode As ext_ConnectMode, ByVal addInInst As Object, ByRef [custom] As Array)
    _application = CType(Application,VBE)
    End Sub

    Private Sub onReferenceItemAdded(ByVal reference As Reference)
        'TODO: Map types found in assembly using reference.
    End Sub

    Private Sub onReferenceItemRemoved(ByVal reference As Reference)
        'TODO: Remove types found in assembly using reference.
    End Sub


    Private Sub BootAddin()
        'Detect change in active window. 
    End Sub

    ''' <summary>
    ''' Implements the OnDisconnection method of the IDTExtensibility2 interface.
    ''' Receives notification that the Add-in is being unloaded.
    ''' </summary>
    ''' <param term='disconnectMode'>
    ''' Describes how the Add-in is being unloaded.
    ''' </param>
    ''' <param term='custom'>
    ''' Array of parameters that are host application specific.
    ''' </param>
    ''' <seealso class='IDTExtensibility2' />
    Public Sub OnDisconnection(ByVal disconnectMode As ext_DisconnectMode, ByRef [custom] As Array)
    End Sub

    ''' <summary>
    ''' Implements the OnAddInsUpdate method of the IDTExtensibility2 interface.
    ''' Receives notification that the collection of Add-ins has changed.
    ''' </summary>
    ''' <param term='custom'>
    ''' Array of parameters that are host application specific.
    ''' </param>
    ''' <seealso class='IDTExtensibility2' />
    Public Sub OnAddInsUpdate(ByRef [custom] As Array)
    End Sub

    ''' <summary>
    ''' Implements the OnStartupComplete method of the IDTExtensibility2 interface.
    ''' Receives notification that the host application has completed loading.
    ''' </summary>
    ''' <param term='custom'>
    ''' Array of parameters that are host application specific.
    ''' </param>
    ''' <seealso class='IDTExtensibility2' />
    Public Sub OnStartupComplete(ByRef [custom] As Array)
        'Boot dispatcher

    End Sub


    ''' <summary>
    ''' Implements the OnBeginShutdown method of the IDTExtensibility2 interface.
    ''' Receives notification that the host application is being unloaded.
    ''' </summary>
    ''' <param term='custom'>
    ''' Array of parameters that are host application specific.
    ''' </param>
    ''' <seealso class='IDTExtensibility2' />
    Public Sub OnBeginShutdown(ByRef [custom] As Array)
    End Sub

    #End Region
End Class
End Namespace

这是用于注册插件的注册表 .key 脚本,请注意,您将需要更改一些设置才能正确注册它。

Windows Registry Editor Version 5.00

[HKEY_CURRENT_USER\Software\Microsoft\VBA\VBE\6.0\Addins\YourAddinName.Connect]
"CommandLineSafe"=dword:00000000
"Description"="Description for your new addin"
"LoadBehavior"=dword:00000000
"FriendlyName"="YourAddinName"


[HKEY_CLASSES_ROOT\CLSID\{YourGeneratedGuid}]
@="YourAddinName.Connect"

[HKEY_CLASSES_ROOT\CLSID\{YourGeneratedGuid}\Implemented Categories]

[HKEY_CLASSES_ROOT\CLSID\{YourGeneratedGuid}\InprocServer32]
@="mscoree.dll"
"ThreadingModel"="Both"
"Class"="YourAddinName.Connect"
"Assembly"="YourAssemblyNameFullTypeName"
"RuntimeVersion"="v2.0.50727"
"CodeBase"="file:///PathToAssembly"

[HKEY_CLASSES_ROOT\CLSID\{YourGeneratedGuid}\ProgId]
@="YourAddinName.Connect"

注意 标记“YourGenerateGuid”必须包含大括号 {},并且与上面 attrib 中的 Guid 相同,标记“YourAssemblyNameFullTypeName”必须是程序集全名,标记“YourAddinName”必须是程序集全名。 Connect”必须与上面属性中设置的 ProgId 相同。

旁注

还发现这很有帮助,可能会节省您几个小时的谷歌搜索时间。

'HKEY_CURRENT_USER\Software\Microsoft\VBA\6.0\Common
'FontFace=Courier New (STRING - Default if missing)
'FontHeight=10 (DWORD - Default if missing)                

It is possible you need to write a com addin using IDTExtensibility2 interface, select the shared addin project template from new project.

EDIT

Otherwise to create this addin from scratch you will need to do the following:

  1. Create a new project class library
  2. Add references to "Extensibility", it should be in the list. You may need to download the PIAs for your version of office. (and perhaps VSTO but i am unsure on this point)
  3. Add references to "Microsoft.Vbe.Interop" again should be with the PIAs.
  4. Check the box "Register for Com Interop" in the properties tab.
  5. OPTIONAL In the debug settings tab change the startup to external program and enter the path to the excel exe in the programfiles folder (if this is intended for excel) this is to allow the project to be debuggable.
  6. OPTIONAL In the command options add a entry to a worksheet, or word doc that will show the addin dialog using a macro on startup, for development this makes sense to streamline the debugging experience. eg "C:\vbe.xlsm"
  7. OPTIONAL Also set the startup path to the worksheet directory eg "C:\"
  8. Implement the interface "IDTExtensibility2" found in "Extensibility" assembly.
  9. Call this class "Connect" (this is just a preference)
  10. Attribute the class with the following

[ComVisible(true),
Guid("YourGeneratedGuid"),
ProgId("YourAddinName.Connect")]

Heres an implementation to get you started, Firstly replace the "YourAddinName" with your AppName and Create a Guid for "YourGeneratedGuid".
You will need to register the Addin into the right Registry location, see the registry keys that follow to get an idea, also replace some vars in the registry keys.

Imports System
Imports System.Drawing
Imports System.Linq
Imports System.Runtime.InteropServices
Imports Extensibility
Imports Microsoft.Vbe.Interop

Namespace VBEAddin


''' <summary>
''' The object for implementing an Add-in.
''' </summary>
''' <seealso class='IDTExtensibility2' />
<Guid("YourGeneratedGuid"), ProgId("YourAddinName.Connect")> _ 
Public Class Connect
    Implements IDTExtensibility2
    Private _application As VBE 'Interop VBE application object


    #Region "IDTExtensibility2 Members"

    ''' <summary>
    ''' Implements the OnConnection method of the IDTExtensibility2 interface.
    ''' Receives notification that the Add-in is being loaded.
    ''' </summary>
    ''' <param term='application'>
    ''' Root object of the host application.
    ''' </param>
    ''' <param term='connectMode'>
    ''' Describes how the Add-in is being loaded.
    ''' </param>
    ''' <param term='addInInst'>
    ''' Object representing this Add-in.
    ''' </param>
    ''' <seealso class='IDTExtensibility2' />
    Public Sub OnConnection(ByVal application As Object, ByVal connectMode As ext_ConnectMode, ByVal addInInst As Object, ByRef [custom] As Array)
    _application = CType(Application,VBE)
    End Sub

    Private Sub onReferenceItemAdded(ByVal reference As Reference)
        'TODO: Map types found in assembly using reference.
    End Sub

    Private Sub onReferenceItemRemoved(ByVal reference As Reference)
        'TODO: Remove types found in assembly using reference.
    End Sub


    Private Sub BootAddin()
        'Detect change in active window. 
    End Sub

    ''' <summary>
    ''' Implements the OnDisconnection method of the IDTExtensibility2 interface.
    ''' Receives notification that the Add-in is being unloaded.
    ''' </summary>
    ''' <param term='disconnectMode'>
    ''' Describes how the Add-in is being unloaded.
    ''' </param>
    ''' <param term='custom'>
    ''' Array of parameters that are host application specific.
    ''' </param>
    ''' <seealso class='IDTExtensibility2' />
    Public Sub OnDisconnection(ByVal disconnectMode As ext_DisconnectMode, ByRef [custom] As Array)
    End Sub

    ''' <summary>
    ''' Implements the OnAddInsUpdate method of the IDTExtensibility2 interface.
    ''' Receives notification that the collection of Add-ins has changed.
    ''' </summary>
    ''' <param term='custom'>
    ''' Array of parameters that are host application specific.
    ''' </param>
    ''' <seealso class='IDTExtensibility2' />
    Public Sub OnAddInsUpdate(ByRef [custom] As Array)
    End Sub

    ''' <summary>
    ''' Implements the OnStartupComplete method of the IDTExtensibility2 interface.
    ''' Receives notification that the host application has completed loading.
    ''' </summary>
    ''' <param term='custom'>
    ''' Array of parameters that are host application specific.
    ''' </param>
    ''' <seealso class='IDTExtensibility2' />
    Public Sub OnStartupComplete(ByRef [custom] As Array)
        'Boot dispatcher

    End Sub


    ''' <summary>
    ''' Implements the OnBeginShutdown method of the IDTExtensibility2 interface.
    ''' Receives notification that the host application is being unloaded.
    ''' </summary>
    ''' <param term='custom'>
    ''' Array of parameters that are host application specific.
    ''' </param>
    ''' <seealso class='IDTExtensibility2' />
    Public Sub OnBeginShutdown(ByRef [custom] As Array)
    End Sub

    #End Region
End Class
End Namespace

Here is the registry .key script to register the Addin, note you will need to change some of the settings in order to register it properly.

Windows Registry Editor Version 5.00

[HKEY_CURRENT_USER\Software\Microsoft\VBA\VBE\6.0\Addins\YourAddinName.Connect]
"CommandLineSafe"=dword:00000000
"Description"="Description for your new addin"
"LoadBehavior"=dword:00000000
"FriendlyName"="YourAddinName"


[HKEY_CLASSES_ROOT\CLSID\{YourGeneratedGuid}]
@="YourAddinName.Connect"

[HKEY_CLASSES_ROOT\CLSID\{YourGeneratedGuid}\Implemented Categories]

[HKEY_CLASSES_ROOT\CLSID\{YourGeneratedGuid}\InprocServer32]
@="mscoree.dll"
"ThreadingModel"="Both"
"Class"="YourAddinName.Connect"
"Assembly"="YourAssemblyNameFullTypeName"
"RuntimeVersion"="v2.0.50727"
"CodeBase"="file:///PathToAssembly"

[HKEY_CLASSES_ROOT\CLSID\{YourGeneratedGuid}\ProgId]
@="YourAddinName.Connect"

NOTE the tokens "YourGeneratedGuid" must have the curly braces {} included and be the same as the Guid in the attrib above, the token "YourAssemblyNameFullTypeName" must be the Assembly full name, the token "YourAddinName.Connect" must be the same ProgId set in the attrib above.

SIDE NOTE

Also found this helpful, might save you couple hours googling.

'HKEY_CURRENT_USER\Software\Microsoft\VBA\6.0\Common
'FontFace=Courier New (STRING - Default if missing)
'FontHeight=10 (DWORD - Default if missing)                
[浮城] 2024-08-23 09:58:15

不幸的是,almog.ori 的步骤对我不起作用。这是我的版本,以帮助将来的人们:

  1. 创建一个名为“VBEAddIn”的 C# 或 VB.NET 类库项目

    使用“项目”、“添加引用...”菜单、“浏览”选项卡添加以下 Interop 程序集作为对项目的引用。

  2. 扩展性 (C:\Program Files\Microsoft Visual Studio 10.0\Visual Studio Tools for Office\PIA\Common\Extensibility.dll) - 如果不存在,请尝试 C:\Program Files (x86)\ if您使用的是 x64 PC。

  3. Microsoft.Office.Interop.Excel (C:\Program Files\Microsoft Visual Studio 10.0\Visual Studio Tools for Office\PIA \Office14\Microsoft.Office.Interop.Excel.dll)

  4. Microsoft.Vbe.Interop (C:\Program Files\Microsoft Visual Studio 10.0\Visual Studio Tools for Office\PIA\Office14\Microsoft.Vbe.Interop.dll)

  5. (可选)Microsoft.Vbe.Interop.Forms (C:\ Program Files\Microsoft Visual Studio 10.0\Visual Studio Tools for Office\PIA\Office14\Microsoft.Vbe.Interop.Forms.dll)

使用以下代码将类添加到项目中:

VB.Net:

Imports Microsoft.Office.Interop
Imports Extensibility
Imports System.Windows.Forms
Imports System.Runtime.InteropServices
Imports Microsoft.Vbe.Interop

<ComVisible(True), Guid("3599862B-FF92-42DF-BB55-DBD37CC13565"), ProgId("VBEAddInVB.Net.Connect")> _
Public Class Connect
    Implements Extensibility.IDTExtensibility2

    Private _VBE As VBE
    Private _AddIn As AddIn

    Private Sub OnConnection(Application As Object, ConnectMode As Extensibility.ext_ConnectMode, _
       AddInInst As Object, ByRef custom As System.Array) Implements IDTExtensibility2.OnConnection
        Try
            _VBE = DirectCast(Application, VBE)
            _AddIn = DirectCast(AddInInst, AddIn)
            Select Case ConnectMode
                Case Extensibility.ext_ConnectMode.ext_cm_Startup
                Case Extensibility.ext_ConnectMode.ext_cm_AfterStartup
                    InitializeAddIn()
            End Select
        Catch ex As Exception
            MessageBox.Show(ex.ToString())
        End Try
    End Sub

    Private Sub OnDisconnection(RemoveMode As Extensibility.ext_DisconnectMode, _
       ByRef custom As System.Array) Implements IDTExtensibility2.OnDisconnection

    End Sub

    Private Sub OnStartupComplete(ByRef custom As System.Array) _
       Implements IDTExtensibility2.OnStartupComplete
        InitializeAddIn()
    End Sub

    Private Sub OnAddInsUpdate(ByRef custom As System.Array) Implements IDTExtensibility2.OnAddInsUpdate

    End Sub

    Private Sub OnBeginShutdown(ByRef custom As System.Array) Implements IDTExtensibility2.OnBeginShutdown

    End Sub

    Private Sub InitializeAddIn()
        MessageBox.Show(_AddIn.ProgId & " loaded in VBA editor version " & _VBE.Version)
    End Sub

End Class

C# :

using System;
using System.Collections;
using System.Collections.Generic;
using System.Data;
using System.Diagnostics;
using System.Linq;
using System.Runtime.InteropServices;
using Extensibility;
using Microsoft.Vbe.Interop;
using System.Windows.Forms;

namespace VBEAddin
{
    [ComVisible(true), Guid("3599862B-FF92-42DF-BB55-DBD37CC13565"), ProgId("VBEAddIn.Connect")]
    public class Connect : IDTExtensibility2
    {
        private VBE _VBE;
        private AddIn _AddIn;

        #region "IDTExtensibility2 Members"

        public void OnConnection(object application, ext_ConnectMode connectMode, object addInInst, ref Array custom)
        {
            try 
            {
                _VBE = (VBE)application;
                _AddIn = (AddIn)addInInst;

                switch (connectMode) 
                {
                    case Extensibility.ext_ConnectMode.ext_cm_Startup:
                        break;
                    case Extensibility.ext_ConnectMode.ext_cm_AfterStartup:
                        InitializeAddIn();

                        break;
                }
            }
            catch (Exception ex) 
            {
                MessageBox.Show(ex.ToString());
            }
        }

        private void onReferenceItemAdded(Reference reference)
        {
            //TODO: Map types found in assembly using reference.
        }

        private void onReferenceItemRemoved(Reference reference)
        {
            //TODO: Remove types found in assembly using reference.
        }

        public void OnDisconnection(ext_DisconnectMode disconnectMode, ref Array custom)
        {
        }

        public void OnAddInsUpdate(ref Array custom)
        {
        }

        public void OnStartupComplete(ref Array custom)
        {
              InitializeAddIn();
        }

        private void InitializeAddIn()
        {
            MessageBox.Show(_AddIn.ProgId + " loaded in VBA editor version " + _VBE.Version);
        }

        public void OnBeginShutdown(ref Array custom)
        {
        }

        #endregion
    }
}

在项目的“项目属性”窗口中:

  1. 在“应用程序”选项卡中,确保程序集名称和根命名空间都设置为“VBEAddIn”。

  2. 在“编译”选项卡中,确保选中“注册 COM 互操作”复选框。我们不会费心使用适当的 regasm.exe 工具手动注册 COM Interop 程序集。但请注意,“注册 COM 互操作”复选框只会将加载项 dll 注册为 32 位 COM 库,而不是 64 位 COM 库。

  3. 在“编译”选项卡的“高级编译选项”按钮中,确保“目标 CPU”组合框设置为“AnyCPU”,这意味着程序集可以作为 64 位或 32 位执行,具体取决于在加载它的执行 .NET Framework 上。

  4. 在“签名”选项卡中,确保未选中“对程序集进行签名”。

接下来添加注册表项,将以下代码片段保存为带有 reg 扩展名的 ASCI 文件,然后双击它以将值添加到注册表中。

重要提示:在执行 reg 文件之前,请更改路径: "CodeBase"="file:///C:\Dev\VBEAddIn\VBEAddIn\bin\Debug\VBEAddIn.dll

Windows Registry Editor Version 5.00

[HKEY_CURRENT_USER\Software\Microsoft\VBA\VBE\6.0\Addins\VBEAddIn.Connect]
"CommandLineSafe"=dword:00000000
"Description"="Description for your new addin"
"LoadBehavior"=dword:00000000
"FriendlyName"="VBEAddIn"


[HKEY_CLASSES_ROOT\CLSID\{3599862B-FF92-42DF-BB55-DBD37CC13565}]
@="VBEAddIn.Connect"

[HKEY_CLASSES_ROOT\CLSID\{3599862B-FF92-42DF-BB55-DBD37CC13565}\Implemented Categories]

[HKEY_CLASSES_ROOT\CLSID\{3599862B-FF92-42DF-BB55-DBD37CC13565}\InprocServer32]
@="mscoree.dll"
"ThreadingModel"="Both"
"Class"="VBEAddIn.Connect"
"Assembly"="VBEAddIn"
"RuntimeVersion"="v2.0.50727"
"CodeBase"="file:///C:\Dev\VBEAddIn\VBEAddIn\bin\Debug\VBEAddIn.dll"

[HKEY_CLASSES_ROOT\CLSID\{3599862B-FF92-42DF-BB55-DBD37CC13565}\ProgId]
@="VBEAddIn.Connect"
  1. " Visual Studio 中的 VBE 插件并打开 Excel。
  2. 打开其 VBA 编辑器 (Alt + F11)。
  3. 转到“加载项”、“加载项管理器...”菜单检查加载项是否已正确注册。
  4. 加载加载项。您应该看到消息框“VBEAddIn.Connect 在 VBA 编辑器中加载”

如果出现此错误:

在此处输入图像描述

无法加载“VBEAddIn”。

将其从可用加载项列表中删除吗?

您可能没有更改路径“CodeBase”=“file:///C:\Dev\VBEAddIn\VBEAddIn\bin\Debug\VBEAddIn.dll”

并检查 CodeBase 密钥是否在注册表中(添加一个字符串regkey 与代码库(如果不存在):

在此处输入图像描述

然后关闭 Office 应用程序,从 Visual Studio 再次构建 VBE AddIn,打开 Office(Excel、Outlook、Word 等)并按 Alt + F11,插件菜单>插件管理器并选择插件并勾选已加载/已卸载。

解决此问题的最后一个技巧:

如果仍然失败,请关闭 Office 应用程序,转到 Visual Studio,“项目属性”>“构建选项卡>勾选“注册 COM 互操作”>构建解决方案并打开 Office Add In > Alt + F11 >插件菜单>插件管理器并单击“已加载/已卸载”。


这个答案使用了我修改过的 Carlo's Quintero (MZTools) 的一些信息,参考: http ://www.mztools.com/articles/2012/MZ2012013.aspx

Unfortunately almog.ori's steps didn't work for me. Here is my version to aid people in the future:

  1. Create a C# or VB.NET Class Library project named "VBEAddIn"

    Add the following Interop assemblies as references to the project, using the "Project", "Add Reference..." menu, "Browse" tab.

  2. Extensibility (C:\Program Files\Microsoft Visual Studio 10.0\Visual Studio Tools for Office\PIA\Common\Extensibility.dll) - if its not there try the C:\Program Files (x86)\ if your using a x64 PC.

  3. Microsoft.Office.Interop.Excel (C:\Program Files\Microsoft Visual Studio 10.0\Visual Studio Tools for Office\PIA\Office14\Microsoft.Office.Interop.Excel.dll)

  4. Microsoft.Vbe.Interop (C:\Program Files\Microsoft Visual Studio 10.0\Visual Studio Tools for Office\PIA\Office14\Microsoft.Vbe.Interop.dll)

  5. (optionally) Microsoft.Vbe.Interop.Forms (C:\Program Files\Microsoft Visual Studio 10.0\Visual Studio Tools for Office\PIA\Office14\Microsoft.Vbe.Interop.Forms.dll)

Add a class to your project with the following code:

VB.Net:

Imports Microsoft.Office.Interop
Imports Extensibility
Imports System.Windows.Forms
Imports System.Runtime.InteropServices
Imports Microsoft.Vbe.Interop

<ComVisible(True), Guid("3599862B-FF92-42DF-BB55-DBD37CC13565"), ProgId("VBEAddInVB.Net.Connect")> _
Public Class Connect
    Implements Extensibility.IDTExtensibility2

    Private _VBE As VBE
    Private _AddIn As AddIn

    Private Sub OnConnection(Application As Object, ConnectMode As Extensibility.ext_ConnectMode, _
       AddInInst As Object, ByRef custom As System.Array) Implements IDTExtensibility2.OnConnection
        Try
            _VBE = DirectCast(Application, VBE)
            _AddIn = DirectCast(AddInInst, AddIn)
            Select Case ConnectMode
                Case Extensibility.ext_ConnectMode.ext_cm_Startup
                Case Extensibility.ext_ConnectMode.ext_cm_AfterStartup
                    InitializeAddIn()
            End Select
        Catch ex As Exception
            MessageBox.Show(ex.ToString())
        End Try
    End Sub

    Private Sub OnDisconnection(RemoveMode As Extensibility.ext_DisconnectMode, _
       ByRef custom As System.Array) Implements IDTExtensibility2.OnDisconnection

    End Sub

    Private Sub OnStartupComplete(ByRef custom As System.Array) _
       Implements IDTExtensibility2.OnStartupComplete
        InitializeAddIn()
    End Sub

    Private Sub OnAddInsUpdate(ByRef custom As System.Array) Implements IDTExtensibility2.OnAddInsUpdate

    End Sub

    Private Sub OnBeginShutdown(ByRef custom As System.Array) Implements IDTExtensibility2.OnBeginShutdown

    End Sub

    Private Sub InitializeAddIn()
        MessageBox.Show(_AddIn.ProgId & " loaded in VBA editor version " & _VBE.Version)
    End Sub

End Class

C#:

using System;
using System.Collections;
using System.Collections.Generic;
using System.Data;
using System.Diagnostics;
using System.Linq;
using System.Runtime.InteropServices;
using Extensibility;
using Microsoft.Vbe.Interop;
using System.Windows.Forms;

namespace VBEAddin
{
    [ComVisible(true), Guid("3599862B-FF92-42DF-BB55-DBD37CC13565"), ProgId("VBEAddIn.Connect")]
    public class Connect : IDTExtensibility2
    {
        private VBE _VBE;
        private AddIn _AddIn;

        #region "IDTExtensibility2 Members"

        public void OnConnection(object application, ext_ConnectMode connectMode, object addInInst, ref Array custom)
        {
            try 
            {
                _VBE = (VBE)application;
                _AddIn = (AddIn)addInInst;

                switch (connectMode) 
                {
                    case Extensibility.ext_ConnectMode.ext_cm_Startup:
                        break;
                    case Extensibility.ext_ConnectMode.ext_cm_AfterStartup:
                        InitializeAddIn();

                        break;
                }
            }
            catch (Exception ex) 
            {
                MessageBox.Show(ex.ToString());
            }
        }

        private void onReferenceItemAdded(Reference reference)
        {
            //TODO: Map types found in assembly using reference.
        }

        private void onReferenceItemRemoved(Reference reference)
        {
            //TODO: Remove types found in assembly using reference.
        }

        public void OnDisconnection(ext_DisconnectMode disconnectMode, ref Array custom)
        {
        }

        public void OnAddInsUpdate(ref Array custom)
        {
        }

        public void OnStartupComplete(ref Array custom)
        {
              InitializeAddIn();
        }

        private void InitializeAddIn()
        {
            MessageBox.Show(_AddIn.ProgId + " loaded in VBA editor version " + _VBE.Version);
        }

        public void OnBeginShutdown(ref Array custom)
        {
        }

        #endregion
    }
}

In the Project properties window of the project:

  1. In the "Application" tab, ensure that both the Assembly name and Root namespace are set to "VBEAddIn".

  2. In the "Compile" tab, ensure that the "Register for COM interop" checkbox is checked. We wont bother with registering assembly for COM Interop manually with the proper regasm.exe tool. However note that the "Register for COM interop" checkbox would only register the add-in dll as 32-bit COM library, not as 64-bit COM library.

  3. In the "Compile" tab, "Advanced Compile Options" button, ensure that the "Target CPU" combobox is set to "AnyCPU", which means that the assembly can be executed as 64-bit or 32-bit, depending on the executing .NET Framework that loads it.

  4. In the "Signing" tab, make sure the "Sign the assembly" is unticked.

Next add the registry Keys, save the below snippet as a ASCI file with a reg extension and double click it to add the values to the registry.

Important Note: Before you execute the reg file, change the path: "CodeBase"="file:///C:\Dev\VBEAddIn\VBEAddIn\bin\Debug\VBEAddIn.dll"

Windows Registry Editor Version 5.00

[HKEY_CURRENT_USER\Software\Microsoft\VBA\VBE\6.0\Addins\VBEAddIn.Connect]
"CommandLineSafe"=dword:00000000
"Description"="Description for your new addin"
"LoadBehavior"=dword:00000000
"FriendlyName"="VBEAddIn"


[HKEY_CLASSES_ROOT\CLSID\{3599862B-FF92-42DF-BB55-DBD37CC13565}]
@="VBEAddIn.Connect"

[HKEY_CLASSES_ROOT\CLSID\{3599862B-FF92-42DF-BB55-DBD37CC13565}\Implemented Categories]

[HKEY_CLASSES_ROOT\CLSID\{3599862B-FF92-42DF-BB55-DBD37CC13565}\InprocServer32]
@="mscoree.dll"
"ThreadingModel"="Both"
"Class"="VBEAddIn.Connect"
"Assembly"="VBEAddIn"
"RuntimeVersion"="v2.0.50727"
"CodeBase"="file:///C:\Dev\VBEAddIn\VBEAddIn\bin\Debug\VBEAddIn.dll"

[HKEY_CLASSES_ROOT\CLSID\{3599862B-FF92-42DF-BB55-DBD37CC13565}\ProgId]
@="VBEAddIn.Connect"
  1. Build the VBE Add-in in Visual Studio and open Excel.
  2. Open its VBA editor (Alt + F11).
  3. Go to the "Add-Ins", "Add-In Manager..." menu to check that the add-in is correctly registered.
  4. Load the add-in. You should see the message box "VBEAddIn.Connect loaded in VBA editor"

If you get this error:

enter image description here

'VBEAddIn' could not be loaded.

Remove it from the list of available Add-Ins?

Its likely you didn't change the path "CodeBase"="file:///C:\Dev\VBEAddIn\VBEAddIn\bin\Debug\VBEAddIn.dll"

And check that the CodeBase key is in the registry (add a string regkey with the CodeBase if it doesn't exist):

enter image description here

Then close down the Office application, build the VBE AddIn again from Visual Studio, Open Office (Excel, Outlook, Word, etc) and Alt + F11, AddIns menu > AddIn Manager and select the AddIn and Tick Loaded/UnLoaded.

Final Trick to overcome this issue:

If that still fails, close the Office app, goto Visual Studio, Project Properties > Build Tab > Tick Register for COM Interop > Build Solution and open the Office Add In > Alt + F11 > AddIns Menu > AddIn Manager and click Loaded/Unloaded.


This answer uses some info from Carlo's Quintero (MZTools) that I've modified, Ref: http://www.mztools.com/articles/2012/MZ2012013.aspx

心清如水 2024-08-23 09:58:15

我还发现此参考对于从 C# 或 VB.NET 制作 VBA DLL 很有帮助:

  1. 创建一个新的 C#(或 VB.Net)项目并选择“类库”作为模板类型。

    使用系统;
    使用 System.Collections.Generic;
    使用 System.Linq;
    使用系统文本;
    
    命名空间 SimpleCalc
    {
        公开课计算
        {
            私有 int numberOne = 0;
            私有 int numberTwo = 0;
    
            公共无效SetNumberOne(int数字)
            {
                数字一 = 数字;
            }
    
            公共无效SetNumberTwo(int数字)
            {
                数字二 = 数字;
            }
    
            // 将两个整数相加
            公共 int 添加()
            {
                返回数字一+数字二;
            }
        }
    }
    
  2. 配置项目属性以使其 COM 可见。

  3. 注册 COM 互操作。
  4. 编译项目。
  5. 将类型库文件复制到 Windows 系统文件夹。
  6. 从 Access VBA 编辑器引用类型库。
  7. 在 VBA 代码中使用 DLL。

    公共函数测试()
        Dim lngResult As Long
    
        Dim objCalc As SimpleCalc.Calc
        设置 objCalc = New SimpleCalc.Calc
    
        objCalc.SetNumberOne (3)
        objCalc.SetNumberTwo (6)
    
        lngResult = objCalc.Add()
    
    结束功能
    

GeeksEngine.com 提供

I also found this reference to be helpful in making a VBA DLL from C# or VB.NET:

  1. Create a new C# (or VB.Net) project and select Class Library as the template type.

    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    
    namespace SimpleCalc
    {
        public class Calc
        {
            private int numberOne = 0;
            private int numberTwo = 0;
    
            public void SetNumberOne(int number)
            {
                numberOne = number;
            }
    
            public void SetNumberTwo(int number)
            {
                numberTwo = number;
            }
    
            // Add two integers
            public int Add()
            {
                return numberOne + numberTwo;
            }
        }
    }
    
  2. Configure project properties to make it COM visible.

  3. Register for COM Interop.
  4. Compile the project.
  5. Copy the type library file to Windows system folder.
  6. Reference the type library from Access VBA editor.
  7. Use the DLL in your VBA code.

    Public Function test()
        Dim lngResult As Long
    
        Dim objCalc As SimpleCalc.Calc
        Set objCalc = New SimpleCalc.Calc
    
        objCalc.SetNumberOne (3)
        objCalc.SetNumberTwo (6)
    
        lngResult = objCalc.Add()
    
    End Function
    

Made available by GeeksEngine.com

素食主义者 2024-08-23 09:58:15

我想您可以从 VBA 代码中调用 .NET DLL(我自己从未真正这样做过)。只需创建一个 VB 类库项目并创建一个在 VBA 中使用的 DLL。

经过快速谷歌搜索后,您似乎需要在“项目属性”->“构建”下设置“Register for Com Interop”= True,但就像我说的,我以前从未真正尝试过这一点。

I would imagine you could call a .NET DLL from your VBA code (never actually done this myself). Just create a VB Class Library project and create a DLL to use in your VBA.

After a quick google it looks like you would need to set "Register for Com Interop" = True under Project Properties->Build, but like I said, I've never actually tried this before.

回忆追雨的时光 2024-08-23 09:58:15

还要注意项目的 Guid(如果是 assamblyInfo.cs 中的 c#)与“Connect”类的 Guid 不同。

具有相同的 Guid 会导致“无法转换为类型库” - 检查时出错:Project Properties >构建选项卡>注册 COM 互操作

Also take care that the Guid of the project (in case of c# in assamblyInfo.cs) is different from the Guid of the Class "Connect".

Having the same Guid results in a "could not be converted to a type library"-error when checking: Project Properties > Build Tab > Register for COM Interop

鹤仙姿 2024-08-23 09:58:15

我完全同意杰里米·汤普森上面的回答。然而,我花了几个小时试图让示例 VBEAddin 工作。直到我在 Connect 类代码中注意到 ProgID 属性为“VBEAddInVB.Net.Connect”,但用于创建 .reg 文件的注册表文本中,所有对程序名称的引用均为“VBEAddIn.Connect”。因此,我尝试将 Connect 类中的 ProgId 属性更改为“VBEAddIn.Connect”,重新构建它,并且成功了!我认为名称必须一致。我希望这可以节省其他人一些时间。

I agree wholeheartedly with Jeremy Thompson’s answer above. However, I spent hours trying to get the example VBEAddin to work. Until I noticed in the Connect Class code that the ProgID attribute was "VBEAddInVB.Net.Connect" but the Registry text that was meant to create a .reg file, had all the references to the program name as “VBEAddIn.Connect”. So I tried changing the ProgId Attribute to “VBEAddIn.Connect” in the Connect Class, rebuilt it, and it worked! I think the names have to be consistent. I hope this saves others some time.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文