View Single Post
 
Old 02-07-2025, 05:13 PM
Guessed's Avatar
Guessed Guessed is offline Windows 10 Office 2016
Expert
 
Join Date: Mar 2010
Location: Canberra/Melbourne Australia
Posts: 4,166
Guessed has a brilliant futureGuessed has a brilliant futureGuessed has a brilliant futureGuessed has a brilliant futureGuessed has a brilliant futureGuessed has a brilliant futureGuessed has a brilliant futureGuessed has a brilliant futureGuessed has a brilliant futureGuessed has a brilliant futureGuessed has a brilliant future
Default

I thought I'd give Gemini.AI a chance to write this code and it did a reasonable job that worked after a few fixes. Try this code which exports all modules as text files (rather than putting the code into a Word document). IMO exported modules is the more efficient way to save the code because you can then import them to a template rather than making a module and copying text in.
Code:
Sub ExportAllVBAModules()

  Dim vbProj As VBProject     'needs reference to Microsoft Visual Basic for Applications Extensibility 5.3
  Dim vbComp As VBComponent
  Dim strFileName As String, strFilePath As String

  ' Set the path where you want to save the exported modules.  ' You can change this to a specific folder or use a file dialog.
  strFilePath = Environ("USERPROFILE") & "\Documents\" ' Example: Saves to Documents folder

  Set vbProj = ThisDocument.VBProject  ' Get the current VBA project.
  For Each vbComp In vbProj.VBComponents  ' Loop through all components in the project.
    ' Check if the component is a module (standard module, class module, or form module).
    If vbComp.Type = vbext_ct_StdModule Or vbComp.Type = vbext_ct_ClassModule Or vbComp.Type = vbext_ct_MSForm Then

      ' Create the file name.  Use the component's name.        ' Replace invalid characters with underscores.
      strFileName = ReplaceInvalidChars(vbComp.Name) & ".bas"   ' Or .cls, .frm as needed.
      strFileName = strFilePath & strFileName ' Combine the path and file name.
      vbComp.Export strFileName    ' Export the component.
      Debug.Print "Exported: " & vbComp.Name & " to " & strFileName 'For debugging.
    End If
  Next vbComp

  MsgBox "All VBA modules exported to: " & strFilePath, vbInformation, "Export Complete"

End Sub

Private Function ReplaceInvalidChars(strName As String) As String
  ' Helper function to replace invalid characters in file names.
  Dim strInvalidChars As String, i As Long
  strInvalidChars = "<>:""/\|?*" ' Invalid characters for file names.
  For i = 1 To Len(strInvalidChars)
    strName = Replace(strName, Mid(strInvalidChars, i, 1), "_")
  Next i
  ReplaceInvalidChars = strName
End Function
PS. You wouldn't be so paranoid if there wasn't all those programmers out to get you
__________________
Andrew Lockton
Chrysalis Design, Melbourne Australia
Reply With Quote