Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save DataStrategist/d8126d619bf3b60d1091 to your computer and use it in GitHub Desktop.
Save DataStrategist/d8126d619bf3b60d1091 to your computer and use it in GitHub Desktop.
' Excel macro to export all VBA source code in this project to text files for proper source control versioning
' Requires enabling the Excel setting in Options/Trust Center/Trust Center Settings/Macro Settings/Trust access to the VBA project object model
' modified to ask what workbook to export stuff from instead of doing it automatically for Activeworkbook.
Public Sub ExportVisualBasicCode()
Const Module = 1
Const ClassModule = 2
Const Form = 3
Const Document = 100
Const Padding = 24
Dim VBComponent As Object
Dim count As Integer
Dim path As String
Dim directory As String
Dim extension As String
Dim fso As New FileSystemObject
Dim wb As Workbook
While WC <> 6 And WC <> 2
For Each w In Workbooks
WC = MsgBox("Export macros and all for: >> " & w.Name & " << ?", vbYesNoCancel)
If WC = 6 Then Set wb = w: Exit For
Next w
Wend
directory = wb.path & "\VisualBasic"
count = 0
If Not fso.FolderExists(directory) Then
Call fso.CreateFolder(directory)
End If
Set fso = Nothing
For Each VBComponent In wb.VBProject.VBComponents
Select Case VBComponent.Type
Case ClassModule, Document
extension = ".cls"
Case Form
extension = ".frm"
Case Module
extension = ".bas"
Case Else
extension = ".txt"
End Select
On Error Resume Next
Err.Clear
path = directory & "\" & VBComponent.Name & extension
Call VBComponent.Export(path)
If Err.Number <> 0 Then
Call MsgBox("Failed to export " & VBComponent.Name & " to " & path, vbCritical)
Else
count = count + 1
Debug.Print "Exported " & Left$(VBComponent.Name & ":" & Space(Padding), Padding) & path
End If
On Error GoTo 0
Next
MsgBox ("Successfully exported " & CStr(count) & " VBA files from: " & wb.Name & Chr(13) & "To: " & directory)
End Sub
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment