Excel 当我收到消息时如何破例;如果找不到指定的对象";
我正在用optionbutton初始化userform,它与变量匹配。 如果变量匹配,则需要打开OptionButton。 OptionButton不能是连续的,并且存在“找不到指定对象”错误 这是excel VBA,我试图破例,但没有成功Excel 当我收到消息时如何破例;如果找不到指定的对象";,excel,vba,Excel,Vba,我正在用optionbutton初始化userform,它与变量匹配。 如果变量匹配,则需要打开OptionButton。 OptionButton不能是连续的,并且存在“找不到指定对象”错误 这是excel VBA,我试图破例,但没有成功 Private Sub UserForm_Initialize() Dim i As Integer, obj As Object, Fruit As String, Meat As String Fruit = "BANANA": Meat = "BEEF
Private Sub UserForm_Initialize()
Dim i As Integer, obj As Object, Fruit As String, Meat As String
Fruit = "BANANA": Meat = "BEEF"
For i = 11 To 23
Set obj = Controls("OptionButton" & i)
If obj Is Nothing Then
Else
If obj.Caption = Fruit Then obj.Value = True
If obj.Caption = Meat Then obj.Value = True
End If
Next i
End Sub
请告诉我如何对此错误进行例外处理。枚举表单元素,并仅对类型为
OptionButton
的表单元素进行操作
Private Sub UserForm_Initialize()
Dim FormElement As Control ' Enumerates the form elements
Dim OptnBtn As OptionButton ' Enumerates OptionButtons
Dim Fruit As String, Meat As String ' Criteria for setting the buttons
Fruit = "BANANA"
Meat = "BEEF"
For Each FormElement In Me.Controls
On Error Resume Next
Set OptnBtn = FormElement
On Error GoTo 0
If Not OptnBtn Is Nothing Then
If OptnBtn.Caption = Fruit Or OptnBtn.Caption = Meat Then
OptnBtn.Value = True
End If
Set OptnBtn = Nothing
End If
Next FormElement
End Sub
for each
/next
语句迭代表单元素,依次为每个表单元素设置FormElement
。对于每个这样的元素,我们尝试将OptnBtn
设置为该元素;对于不是选项按钮的元素,这将失败并将OptnBtn
设置为Nothing
请注意,在一个组中不能选择多个
OptionButton
True。如果要在表单中选择两个或多个选项按钮,则它们必须位于不同的组中。如果我将obj更改为MSForms.Control,则仍然会出现相同的错误。@Urderboy:比如什么?