2017-04-04 48 views
2

我不会很长一段时间使用VBA ....我有这种形式在Access 2016访问2016 VBA文本框为空

enter image description here

当我试图通过我来访问不同的文本框.Controls收集并将其转换为一个TextBox对象,我得到一个空引用,但它的一些属性是有效的(如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_" 

回答

3

要获取的类型,使用TypeName这样的:

If TypeName(ctrl) = "TextBox" Then 

并确保tb采取的形式一个Textbox对象,使用此

Set tb = Controls(ctrl.Name) 
3

您还没有显示你正在使用的类,但假设它LO这样的事情:

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

但你的代码做不必要的铸造,使用匈牙利命名(呸!),并依赖于域名为“Txt_”的第4个字符,可以写成:

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 in If TypeOf ctrl Is Access.TextBox Then来确定控制是否为TextBox

+0

谢谢,我的错误是忘记了在InnerTextBox中设置属性:( 小OT:我有另一个问题[这里](http://stackoverflow.com/questions/43219351/access-2016- set-control-events-at-runtime)你能知道为什么会发生这种情况吗? – Barzo