PDA

View Full Version : how to make exception when I get message of “if could not find the specified object”



vocedicore
02-02-2019, 08:45 PM
I'm initializing userform with optionbutton that matching with variable. OptionButton need to be turned on if variable is matching. OptionButton can not be continuous and having error with "Could not find the specified object".
This is excel VBA, I was trying to make exception, but didn't work.

Private Sub UserForm_Initialize()
Dim i As Integer, obj As MSForms.Control, Fruit As String, Meat As String
Fruit = "BANANA": Meat = "BEEF":
For i = 11 To 23
Set obj = Controls("OptionButton" & i)
If Not obj Is Nothing Then
If obj.Caption = Fruit Then obj.Value = True
If obj.Caption = Meat Then obj.Value = True
End If
Next i
End Sub

please give me a comment how to make exception for this error.

mikerickson
02-03-2019, 01:00 AM
This should work

Private Sub UserForm_Initialize()
Dim i As Integer, oneControl As MSForms.Control, Fruit As String, Meat As String
Fruit = "BANANA": Meat = "BEEF":
For Each oneControl In Me.Controls
If TypeName(oneControl) = "OptionButton" Then
oneControl.Value = ((oneControl.Caption = Fruit) Or (oneControl.Caption = Meat))
End If
Next oneControl
End Sub

vocedicore
02-03-2019, 06:21 PM
This is genius , I love this part.

oneControl.Value = ((oneControl.Caption = Fruit) Or (oneControl.Caption = Meat))Me.Controls

vocedicore
02-03-2019, 06:22 PM
This is genius , I love this part.


oneControl.Value = ((oneControl.Caption = Fruit) Or (oneControl.Caption = Meat))Me.Controls