2013-09-23 23 views
0

/Next循環我有UserForm4含有CheckBox1 ... 19,並且還OptionButton1 ... 3,用TextBox1中,沿着CommandButton1的,2.錯誤結束對於通過的CheckBox

當選項按鈕1 =真欲環通過所有複選框並將其設置爲True。

我得到狀態「找不到對象」和我= 21,n = 23的錯誤。當我只有19個CheckBox時,它們如何變得那麼高?

謝謝!

Private Sub OptionButton1_Click() 

Dim ctrl As Control 
Dim i As Integer 
Dim n As Integer 

n = 0 

For Each ctrl In UserForm4.Controls 
    If TypeOf ctrl Is MSForms.CheckBox Then 
     n = n + 1 
    End If 
Next ctrl 

For i = 1 To n 
    If UserForm4.Controls("CheckBox" & i) = False Then 
     UserForm4.Controls("CheckBox" & i) = True 
    End If 
Next i 

End Sub 

回答

1

您是否最初創建了19個以上並刪除了一些?每個VBA對象都有一個唯一的名稱。按照你這樣做的方式做這件事可能會導致各種各樣的問題。

例如,如果您創建了10個CheckBox並將其中的8個刪除,剩下的兩個可能會被命名爲Checkbox8和Checkbox9。所以你的循環根本不會觸及它們。

而且,爲什麼不這樣做如下:

Private Sub OptionButton1_Click() 

Dim ctrl As Control 
Dim i As Integer 
Dim n As Integer 

n = 0 

For Each ctrl In UserForm4.Controls 
    'this will make your problem really obvious 
    debug.print ctrl.name 
    If TypeOf ctrl Is MSForms.CheckBox Then 
     ctrl.value = True 
    End If 
Next ctrl 


End Sub