Access 2016 VBA TextBox为空

时间:2017-04-04 21:19:51

标签: vba access-vba ms-access-2016

我很长时间没有使用VBA ....我在Access 2016中有这个表单

enter image description here

当我尝试通过Me.Controls集合访问各种TextBox并将其转换为TextBox对象时,我得到一个Null引用但是它的一些属性是有效的(例如.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

我想念一下吗? 另外,有没有办法获得控件的类型,而不是使用

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

2 个答案:

答案 0 :(得分:3)

要获取类型,请使用TypeName,如下所示:

If TypeName(ctrl) = "TextBox" Then

为了确保tb采用Textbox对象的形式,请使用此

Set tb = Controls(ctrl.Name)

答案 1 :(得分:3)

您还没有显示您正在使用的课程,但假设它看起来像这样:

Private WithEvents f_EH As Access.Form
Private WithEvents f_TB As Access.TextBox

Public Property Set EventsHandler(frm As Access.Form)
  Set f_EH = frm
End Property

Public Property Set InnerTextBox(ctl As Access.TextBox)
   Set f_TB = ctl
End Property

如果我使用具有该结构的类,则帖子中的代码可以正常工作。但请注意,我已将InnerTextBox属性的预期类型明确设置为Access.TextBox

但你的代码做了不必要的转换,使用匈牙利语命名(哎呀!),并依赖名称的前4个字符&#34; Txt _&#34;并且可以写成:

  Dim ctrl As Control
  Dim evTb As clsEventTextBox

  Set m_TbColl = New Collection

  For Each ctrl In Me.Controls
    If TypeOf ctrl Is Access.TextBox Then
      'Create the TextBox wrapper
      Set evTb = New clsEventTextBox
      Set evTb.EventsHandler = Me

      Set evTb.InnerTextBox = ctrl  'Just pass the ctrl reference without casting

      m_TbColl.Add evTb, ctrl.Name
    End If
  Next

请注意TypeOf中使用If TypeOf ctrl Is Access.TextBox Then来确定控件是否为TextBox