KentBurel
Board Regular
- Joined
- Mar 27, 2020
- Messages
- 68
- Office Version
- 2019
- Platform
- Windows
This is not a question but a contribution. I have been writing VBA code to automate a business process. I needed a way to document all the code I've written. So I wrote this sub that reads each codemodule in the project and writes it to a word document.
VBA Code:
Option Explicit
Sub DocumentVBA()
' First step is to setup to word environment
Dim wdApp As Word.Application
Dim VBProj As VBIDE.VBProject
Dim VBComp As VBIDE.VBComponent
Dim CodeMod As VBIDE.CodeModule
Dim codify_time As String
Dim filename As String
Set VBProj = Workbooks("LogicAndAccuracyTesting.xlsm").VBProject
Set wdApp = New Word.Application
With wdApp
.Visible = True
.Activate
' Create a new document
.Documents.Add
' Adjust Heading 1 style so that each module starts on a new page
With ActiveDocument.Styles("Heading 1").ParagraphFormat
.SpaceAfter = 12
.PageBreakBefore = True
End With
' Adjust Normal style so that everything is single spaced.
With ActiveDocument.Styles("Normal").ParagraphFormat
.SpaceBefore = 0
.SpaceAfter = 0
.LineSpacingRule = wdLineSpaceSingle
End With
End With
' Now access the vba components
For Each VBComp In VBProj.VBComponents
If VBComp.Type = vbext_ct_StdModule Then
' Write out the name of the component with the style of Header 1
With wdApp.Selection
.Style = ActiveDocument.Styles("Heading 1")
.TypeText Text:="VB Code Module for " & VBComp.Name
.TypeParagraph
End With
Set CodeMod = VBComp.CodeModule
If CodeMod.CountOfLines <> 0 Then
With wdApp.Selection
.Style = ActiveDocument.Styles("Normal")
.TypeText Text:=CodeMod.Lines(1, CodeMod.CountOfLines)
.TypeParagraph
End With
End If
End If
Next VBComp
' Now set landscape mode with narrow margins
With wdApp.Selection.PageSetup
.Orientation = wdOrientLandscape
.TopMargin = InchesToPoints(0.5)
.BottomMargin = InchesToPoints(0.5)
.LeftMargin = InchesToPoints(0.5)
.RightMargin = InchesToPoints(0.5)
.HeaderDistance = InchesToPoints(0.5)
.FooterDistance = InchesToPoints(0.5)
.PageWidth = InchesToPoints(11)
.PageHeight = InchesToPoints(8.5)
End With
' Time to save and close the word document
codify_time = Format(Now, "yyyymmdd_hhmmss")
filename = ThisWorkbook.Path & "\Excel VBA Code." & codify_time & ".docx"
With wdApp
.ActiveDocument.SaveAs2 (filename)
.ActiveDocument.Close
.Quit
End With
Set wdApp = Nothing ' We are done with word
End Sub