2017-08-07 55 views
0

我有動態複選框(編程) 下面是我的代碼如何檢查userform複選框是否被選中;哪些是動態創建的?

Dim Rows As Integer 
Dim toppart As Integer 
Dim Opt As Variant 
Dim x As Integer 

On Error Resume Next 
toppart = 20 

UpdateRow = Application.WorksheetFunction.CountA(ActiveSheet.Range("C3:CU3")) 

For x = 3 To UpdateRow 

Set Opt = Te.Controls.Add("Forms.CheckBox.1", "CheckBox" & x, True) 

Opt.Caption = ActiveSheet.Cells(x, "C").Value 

Opt.Width = 70 
Opt.Height = 18 
Opt.Left = 18 

Opt.Top = toppart 
toppart = toppart + 20 
Next 

我知道,如果複選框被通過控制設置我的代碼看起來像這樣一個窗體:

If (CheckBox1.Value = False) Or (CheckBox2.Value = False) Then MsgBox "You must select alteast 2 checkboxes", vbCritical

但是當複選框被動態創建時,我想不出一個有效的方法來做到這一點。請任何建議或幫助非常感謝,謝謝。

回答

1

未經測試,但您可能會循環控制表單,檢查每個是否爲複選框,如果是,請詢問它是否爲.Value,並計算「已選中」複選框的總數,如果該數字爲LTE 1,那麼你提高你的警告/ MsgBox

Dim checked as Long 
Dim ctrl as Object 
For Each ctrl in Me.Controls 
    If TypeName(ctrl) = "CheckBox" Then 
     If ctrl.Value = True Then 
      checked = checked + 1 
     End If 
    End If 
Next 
If checked <= 1 Then 
    MsgBox "You must select alteast 2 checkboxes", vbCritical 
    Exit Sub 
End If 
+1

'如果類型名(CTRL)=「複選框」 Then'是正確的語法 – 2017-08-07 16:13:00

+0

感謝@ThomasInzina –

+0

非常感謝它的工作,但是,消息框仍然顯示即使我選擇了至少2個複選框 –

相關問題