【问题标题】:Access 2016 VBA TextBox is NullAccess 2016 VBA 文本框为空
【发布时间】:2017-04-04 21:19:51
【问题描述】:

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

当我尝试通过 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_"

【问题讨论】:

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


    【解决方案1】:

    要获取类型,请像这样使用TypeName

    If TypeName(ctrl) = "TextBox" Then
    

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

    Set tb = Controls(ctrl.Name)
    

    【讨论】:

      【解决方案2】:

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

      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 个字符是“Txt_”并且可以写成:

        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
      

      注意If TypeOf ctrl Is Access.TextBox ThenTypeOf的使用判断控件是否为TextBox

      【讨论】:

      • 谢谢,我的错误是忘记了 InnerTextBox Set 属性中的“Set” :( Little OT:我已经发布了另一个问题here你知道为什么会这样吗?
      猜你喜欢
      • 2022-01-11
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-12-01
      • 2021-12-21
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多