2017-04-04 94 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