By Björn Stiel, CTO at Zoomer Analytics (Dec 1, 2017)
Exporting your VBA code
Exporting your VBA modules into stand-alone .bas files is a simple and effective way to make Git aware of code inside your Excel workbooks. The goal is to end up with a separate .bas file for each of your VBA modules so that you can benefit from the Git functionalities.
One common way to achieve this is via Excel’s Workbook.AfterSave (or Workbook.BeforeSave) event. Every time you hit “save” in Excel, some VBA code is executed and saves a copy of your workbook’s VBA content to the filesystem. You end up with your VBA files alongside your workbook which can then be pushed to your Git server.
There are a few downsides to using Excel events. You are dependent on Excel, so if you copy your workbook from an email or another folder into your Git repository folder, your VBA export function will not run. Distributing the export function (either via copy and paste or as an Addin) and ensuring it runs reliably is another pain point.
An alternative approach is to exploit Git’s built-in hooks. Hooks are programs you can place in a hooks directory to trigger actions at certain points in Git’s execution. You can find a list of available hooks in https://git-scm.com/docs/githooks. We will use the pre-commit hook to do the following when you call git commit:
extract the VBA modules from your workbook and write them as .bas files to your repository
add these VBA files to your commit via git add *.bas
finally execute the git commit command
A Python script to extract your VBA code
We use the Python package oletools to extract the VBA code from the Excel file (in fact, this works for any MS Office file). Thus, we no longer have to resort to Excel itself to get hold of the VBA code.
Our script requires Python 3 and oletools. oletools can be installed via pip, Python’s package manager: pip install -U oletools.
Create a file named pre-commit.py in the .git/hooks folder inside your repository and add the following code: