Category Archives: Excel

Add VBA to Excel file at runtime

This snippet demonstrates how you can add VBA code to an Excel file at run time.


In this snippet I am using Microsoft Excel 2013 with the Microsoft Excel 15.0 object library.

Before you can use this code, you will have to change a setting within Microsoft Excel to authorise the use of the VBA Project Object Model from external programs. This is a security feature to protect end users from malicious programs and is disabled by default. If you do not enable this feature then the code below will result in an exception stating “Programmatic access to Visual Basic Project is not trusted” as soon as you attempt to reference the VBA environment.

Enabling trust to the VBA Project Object Model

  1. Open Excel and access the Options section.
  2. Open Excel and access the Options section.
  3. Click the Trust Center Settings button
  4. Select the Macro Settings section
  5. Tick the box labelled “Trust access to the VBA project object model”

The code

You will need the following Imports statements: