2017-03-23 70 views
0

我正在以編程方式創建基於工作表範圍內的行數(當前設置爲測試的固定編號)的用戶窗體。 然後用戶選中他們想要檢查的方框,然後單擊命令按鈕。Excel VBA用戶表單複選框訪問

用戶窗體,如下面的代碼運行,有一個命令按鈕和一個複選框手動添加。其他複選框以編程方式添加。 我無法弄清楚如何從有問題創建的複選框中獲取值。我只是得到一個錯誤,「測試箱」沒有定義。 我知道我錯過了一些簡單的...

有什麼想法? 謝謝!

Option Explicit 

Private Sub updateTablesBtn_Click() 
    If CheckBox1.Value = True Then 
     MsgBox "true" 
    End If 

    If testBox.Value = True Then 
     MsgBox "true" 
    End If 
End Sub 

Private Sub UserForm_Initialize() 
    Dim chkBox As MSForms.CheckBox 

    With formTableUpdate 
     .Width = 150 
     .Height = 200 '15 + 20 * (noOfVariants + 1) + 30 
    End With 

    Set chkBox = formTableUpdate.Controls.Add("Forms.CheckBox.1") 
    With chkBox 
     .Name = "testBox" 
     .Caption = "test" 
     .Left = 5 
     .Top = 10 
    End With 

    With updateTablesBtn 
     .Caption = "Update Tables" 
     .Height = 25 
     .Width = 76 
     .Left = 38 
     .Top = 30 
    End With 

End Sub 

回答

1

試試這個:

Dim chkBox As Control 

For Each chkBox In formTableUpdate.Controls 
    If chkBox.Name = "testBox" Then 
     MsgBox chkBox.Caption & " has the value " & chkBox.Value 
    End If 
Next chkBox