How to add a label to the header section of an MS Access form dynamically using VBA

This fully commented procedure, AddAHeaderLabelToAFrom, adds a label text to the header section of a given form. The code also dynamically adds an event procedure to the label, when the label is double clicked, the form will close. This procedure is part of MAARS implementation. Feel free to copy it and use it in your own automation program – however, please give proper credit to the MAARS team.

Public Sub AddAHeaderLabelToAFrom(frmName As String, lblName As String, lblText As String)
'   Creation date: May 6 2021 Created by: BA
'   Comments: Part of MAARS
'   Purpose: This sub will add a label text to the header section of a given form
'   It will also add an event procedure to close the form when the header label is double clicked

Dim frm As Form, strProc As String, mdl As Module
Set frm = Forms(frmName)
Set mdl = Forms(frmName).Module 'Get the module of the form and store it in mdl variable

If ControlExists(lblName, frmName) = False Then ' Check if the label already exists in the form
         Set ctlLabel = CreateControl(frmName, acLabel, Section:=acHeader, Width:=frm.Width / 3, _
            Height:=420, Left:=frm.Width * 0.4, Top:=100)
            ctlLabel.Name = lblName
            ctlLabel.Caption = StrConv(lblText, vbProperCase)
            ctlLabel.ControlTipText = "Double Click to Close"
            ctlLabel.FontSize = 18
            strProc = ctlLabel.Name & "_DblClick"
            
            'Add the DblClick Event Procedure and attach it to the label
            lngReturn = mdl.CreateEventProc("DblClick", ctlLabel.Name)
            mdl.InsertLines lngReturn + 1, vbTab & "DoCmd.close "

End If

End Sub

This is a complimentary article written by the MAARS team for the MAARS user community. Code in this article drives the operation of MAARS (MS Access Application wRiting Software). MAARS is an intelligent automation program that speeds up MS Access Application Development by 10x, 20x or 100x times. To learn more about MAARS, click here.

Disclaimer:

Some information included in this article may have been sourced from other publicly available websites and blogs. In such cases, credit goes to those authors for the original ideas and thoughts, but we do take credit for putting valuable information together and improve the efficiency of other office developers.