首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >当我收到“如果找不到指定的对象”信息时如何进行异常处理

当我收到“如果找不到指定的对象”信息时如何进行异常处理
EN

Stack Overflow用户
提问于 2019-02-03 11:36:55
回答 1查看 81关注 0票数 0

我正在用匹配变量的optionbutton初始化userform。如果变量匹配,则需要打开OptionButton。OptionButton不能连续,并出现错误“找不到指定的对象”。

这是excel VBA,我试着去做异常,但是不起作用。

代码语言:javascript
复制
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

请给我一个意见,如何为这个错误做例外。

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2019-02-03 15:36:09

枚举表单元素,并仅对OptionButton类型的表单元素进行操作。

代码语言:javascript
复制
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。如果您希望在一个表单中选择两个或多个选项按钮,它们必须位于不同的组中。

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/54499740

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档