Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Create a macro for Microsoft Access via Interop

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.

like image 415
Middas Avatar asked Dec 05 '25 19:12

Middas


1 Answers

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.
}
like image 117
Middas Avatar answered Dec 08 '25 17:12

Middas



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!