2016-09-23 26 views
0

我想構建一個代碼,如果所有複選框在我的用戶窗體中留空,它將警告用戶一個消息框。msgbox當所有複選框爲空

有關如何引用一個用戶窗體中的所有複選框控件來構建此代碼的任何幫助,將不勝感激。

下面是我嘗試過的代碼的一個例子,但它不起作用。

Dim Allcheckbox As Variant 

Allcheckbox = Array("checkbox1", "checkbox2", "checkbox3", "checkbox4", "checkbox5", "checkbox6") 
If Controls(Allcheckbox).Value = False Then 
    MsgBox ("Please select a comparison criteria.") 
End If 

回答

0

謝謝你的幫助Asher!

我最終使用下面的代碼提供了一個解決方案。

Dim x As Integer 

    x = 0 

    For Each cCont In Me.Controls 
     If TypeName(cCont) = "CheckBox" Then 
      If cCont.Value = True Then 
       x = x + 1 
      End If 
     End If 
    Next 

    If x = 0 Then 
     MsgBox ("Please select a comparison criteria.") 
    End If 
0

我會遍歷數組並檢查每個複選框的值。如果任何有值=真,那麼我們設置一個布爾值爲true。這在函數中會更好,您可以傳遞數組,然後可以在傳遞true時立即使用Exit函數。

ctrlSelect = False 
For Each ctrl In form.Controls 
    If TypeName(ctrl) = "CheckBox" Then 
     If crtl.value = "True" Then 
      ctrlSelect = True 
     End If 
    End If 
Next ctrl 

If Not ctrlSelect Then 
    MsgBox ("Please select a comparison criteria.") 
    Exit Sub 
End If