Home » excel » How to have Excel to run VBA code saved in a text file?

How to have Excel to run VBA code saved in a text file?

Posted by: admin May 14, 2020 Leave a comment

Questions:

Instead of having the VBA code saved in a module inside the Excel file, I would like to have the code saved in a text file, for example module1.vba. In Excel, module1.vba would be loaded or imported and run as it was a normal module.

Is that possible? How to do that?

In Excel, in the VBA editor, there is the option Insert > File... in the menu that does sort of what I want, but I don’t know how to automate that with a minimal VBA code to load the real code saved as text.

Reason for this is to allow code revision control using text based applications like git.

— edit —

This answer shows a good alternative work around. However I’m still not too happy in duplicating things.

How to&Answers:

You can easily import a VBA file using a simple one-liner:

Application.VBE.ActiveVBProject.VBComponents.Import "C:\Path\To\File.bas"

This works with files exported from the VBA IDE, which include information like module name and other properties that can be configured on a per-module basis.

You need to enable Trust access to the VBA project object model for this to work. You can find that in the trust center settings, under Macro Settings.