Create a macro for Microsoft Access via Interop

2019-02-18 14:36发布

问题:

Is it possible to create a new macro using C# using the Interop library in Microsoft Access in a similar fashion as Word, Excel, or PowerPoint? In the other applications, you have access to Microsoft.Vbe.Interop._VBComponent, which allows you to inject new macros, through the Document, Worksheet, or Presentation classes. It doesn't look like Access has anything similar to this. Access has an AllMacros list, but it appears to be read-only. I know how to execute the macro once it's in the project, but I need to be able to add macros dynamically. I would greatly appreciate anyone that could point me in the correct direction.

回答1:

Taken from answers.microsoft.com:

A macro in Access is a special database object, unlike in other Office applications where a macro is simply a VBA procedure without arguments. As far as I know you can't create an Access macro programmatically. -HansV MVP (April 27, 2011)

There is another answer posted at the same question that says you can create new code/VBA objects using the VB Extensibility Library.



回答2:

Because of HK1's answer, I was able to do exactly what I needed. I wanted to post my code because there is little to no information anywhere on how to do this. I will leave HK1's post marked as the answer because he is what lead me to this.

Programmatically adding VB Modules to MS-Access via Interop

try
{
    Microsoft.Office.Interop.Access.Application accessApp = new Microsoft.Office.Interop.Access.Application();
    accessApp.Visible = true;

    accessApp.OpenCurrentDatabase(filePath);

    // Get the active VBProject item
    VBProject project = accessApp.VBE.VBProjects.Item(1);

    VBComponent module = project.VBComponents.Add(vbext_ComponentType.vbext_ct_StdModule);

    module.CodeModule.AddFromString(script);
}
catch (Exception ex)
{
    // Trust or the VBA Project Module has not been enabled.
}