Search code examples
ms-accessvbams-access-2016

Access 2016 VBA TextBox is Null


I don't use VBA from long time....I have this form in Access 2016

enter image description here

When I try to access to the various TextBoxes through the Me.Controls Collection and convert it to a TextBox object, I get a Null reference but some its properties are valid (eg. tb.Name)

Private Sub Form_Load()
  Dim ctrl As Control
  Dim tb As TextBox
  Dim evTb As clsEventTextBox

  Set m_TbColl = New Collection

  For Each ctrl In Me.Controls
    If Left$(ctrl.Name, 4) = "Txt_" Then
      Set tb = ctrl
      'Create the TextBox wrapper 
      Set evTb = New clsEventTextBox
      Set evTb.EventsHandler = Me

      Set evTb.InnerTextBox = tb  <----- HERE tb Is NULL

      m_TbColl.Add evTb, ctrl.Name
    End If
  Next
End Sub

I miss something?
Also, is there a way to get the Type of a Control instead of using

Left$(ctrl.Name, 4) = "Txt_"

Solution

  • To get the type, use TypeName like this:

    If TypeName(ctrl) = "TextBox" Then
    

    And to ensure tb takes the form of a Textbox object, use this

    Set tb = Controls(ctrl.Name)