How to check if a control (such as a button, a textbox) already exists in an MS Access Form

This function, ControlExists, checks if a control object already exists in a given form. This is a must have function if you are writing MS Access Form or Report dynamically. Before adding a control to a form, you can use this function to check if it already exists and then decide whether to add or update the control. This function is used as part of MAARS implementation. Feel free to copy it and use it in your own automation program – how please give proper credit to the MAARS team.


Function ControlExists(ControlName As String, FormName As String, _
Optional blnSubform As Boolean, Optional strParentform As String) As Boolean
Dim strTest As String
On Error Resume Next

Select Case blnSubform 'Check if the caller is working with a SubForm or not
    Case True ' If a subform is given, look for the control in the subform
        strTest = Forms(strParentform)(FormName).Form(ControlName).Name
        ControlExists = (Err.Number = 0) ' Err.Number=0 means, no error and the control exists in the subform
    Case Else ' The caller has passed a main form (not a subform)
        strTest = Forms(FormName)(ControlName).Name
        ControlExists = (Err.Number = 0) ' Err.Number=0 means, no error and the control exists in the form
End Select
End Function

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.