Last Updated 11 March 2022
This article describes different methods of viewing the VBA code for a form or individual procedure
1. View Form Code
a) In design view, click the View Code button on the Form Design ribbon
b) Add a button to the form and add this code to the button click event
DoCmd.OpenModule "Form_" & Me.Name
2. View Procedure Code
a) In design view, click the ellipsis button (...) in the property sheet for a form event
b) You can also use VBA to open the code for a named procedure.
To do so, you will first need to add the Microsoft Visual Basic for Applications Extensibility 5.3 reference library
Next add the following code to a standard module:
Option Compare Database
Option Explicit
'This code requires the reference library: Microsoft Visual Basic for Applications Extensibility 5.3
'=======================================
Public Function GetVBP() As VBProject
'Gets the current VB project
Dim fileName As String
Dim vbps As VBProjects
fileName = CurrentDb.Name
Set vbps = Application.VBE.VBProjects
'Debug.Print GetVBP
For Each GetVBP In vbps
If GetVBP.fileName = fileName Then
Exit Function
End If
Next
End Function
'=======================================
Public Function ViewCode(ByVal formName As String, ByVal callbackName As Variant) As Boolean
'Used to view a named code procedure in a specified form
Dim VBP As VBIDE.VBProject
Dim gotoLine As Long
Dim code As String
CloseAllVBEWindows
With Application.VBE
.MainWindow.Visible = True
Set VBP = GetVBP
With VBP.VBComponents("Form_" & formName)
gotoLine = .CodeModule.ProcBodyLine(callbackName, vbext_pk_Proc)
.CodeModule.CodePane.SetSelection gotoLine, 1, gotoLine, 1
'Debug.Print .CodeModule.Lines(gotoLine, 1)
End With
End With
End Function
'=======================================
Function CloseAllVBEWindows()
'closes all VBE windows except this one!
'requires VBA reference library 'Microsoft Visual Basic for Applications Extensibility'
On Error GoTo Err_Handler
Dim vbWin As VBIDE.Window
For Each vbWin In Application.VBE.Windows
If (vbWin.Type = vbext_wt_CodeWindow Or _
vbWin.Type = vbext_wt_Designer) And _
Not vbWin Is Application.VBE.ActiveWindow Then
vbWin.Close
End If
Next
Exit_Handler:
Exit Function
Err_Handler:
If Err.Number = 424 Then Resume Next 'object required
MsgBox "Error " & Err.Number & " in CloseAllVBEWindows procedure: " & Err.Description
Resume Exit_Handler
End Function
Typical usage:
To view the code for the click event of a cmdPrint button on a form frmMain, add code like this to another button on the form:
Private Sub cmdCodePrint_Click()
ViewCode "frmMain", "cmdPrint_Click"
End Sub
For example, see the view code </> buttons used with my Control the Application Interface example application.
Colin Riddington Mendip Data Systems Last Updated 11 March 2022