我正在用匹配变量的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"
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请给我一个意见,如何为这个错误做例外。
发布于 2019-02-03 15:36:09
枚举表单元素,并仅对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 Subfor each / next语句遍历表单元素,依次为每个表单元素设置FormElement。对于每个这样的元素,我们尝试将OptnBtn设置为该元素;对于不是选项按钮的元素,这将失败,并将OptnBtn设置为Nothing。
请注意,您不能在一个组中选择多个OptionButton True。如果您希望在一个表单中选择两个或多个选项按钮,它们必须位于不同的组中。
https://stackoverflow.com/questions/54499740
复制相似问题