Is there a place to store VBA code that's accessible to all Microsoft Office products..?

前端 未结 2 1158
天涯浪人
天涯浪人 2021-01-23 01:09

Is there a way of storing VBA source code that\'s common and accessible to all Microsoft Office products..? I have a variety of functions which I use in both Access and Excel, a

相关标签:
2条回答
  • 2021-01-23 01:40

    I know I could do something like write a class/ocx/addin in VB6 or DotNet, compile it, and reference it in my VBA projects, but I was hoping for something more simple.

    Unfortunately that's your best bet.

    As you know VBA code is hosted, wrapped-up in a host document: a VBA add-in is still tied to its host document (.xlam, etc.), and as such can't be shared with another host.

    In VBA-land what's meant to be shared between VBA projects, is type libraries - things you compile separately from the VBA project, and reference from as many projects as you like.

    If you have a VB6 IDE, you can compile a 32-bit DLL that VBA projects can reference. The problem is that it won't work with 64-bit hosts - the solution is a .NET type library, written in the .NET language of your choice, made COM-visible. Note that COM-compatibility does restrict what you can expose in your API: for example you can't expose generics, and method overloads will look weird.

    If a type library isn't an avenue you wish to explore, then your choices are rather limited, and IMO sub-optimal.

    IMO the only thing that can "work" is a bunch of exported code files in some common folder, and the VBA projects that need to use that code need to literally import these code files. The risk here being, that if you make any changes, other VBA projects using an unmodified version of that code will not "see" these changes, IOW by doing that you're multiplying the number of times you need to fix a bug by the number of projects using that code.

    Or you could have some code that uses the VBIDE extensibility type library to ensure the set of imported modules always match exactly with the exported files in that common location.

    0 讨论(0)
  • 2021-01-23 01:44

    If you want to use VBA in the same Office program (e.g. one Excel file to another, or one Access file to another), you don't need to use any special kind of file. You can add a reference to an external database or worksheet with macro's enabled.

    Navigate Tools - References - Browse - Excel/Access file - Add the file

    See the following screenshot:

    You can't use files across different Office applications this way, but you shouldn't. Each application has different built-in functions, so your code is likely incompatible anyway.

    0 讨论(0)
提交回复
热议问题