【问题标题】:How do I avoid Userform Combobox runtime error?如何避免 Userform Combobox 运行时错误?
【发布时间】:2021-12-23 06:21:41
【问题描述】:

希望是一个简单的问题。我有一些在 Combobox_Change() 期间运行的组合框的简单代码。

Private Sub ComboBox1_Change()
If ComboBox1.Value = "" Then
Label3.Caption = ""

Else

Label3.Caption = Worksheets("Currency").Cells.Find(UserForm1.ComboBox1.Value).Offset(0, -1).Value



End If

End Sub

Private Sub UserForm_Initialize()
ComboBox1.List = [Currency!C2:C168].Value
Label3.Caption = ""
End Sub

但是,当您输入不属于声明的组合框范围的内容时,它会引发运行时错误“未设置对象变量”。我如何愚蠢地证明这个组合框,以及当任何不属于选择范围的不规则条目恢复为“”空时?还是弹出错误框提示“输入无效”?

【问题讨论】:

  • 组合框ListItem 是否填充了有效条目,以便用户必须在列表中进行选择?如果是这样,请将组合框的 Style 属性更改为 fmStyleDropDownList?

标签: excel vba combobox userform


【解决方案1】:

如果Find 找不到任何东西,它会返回一个空对象。该返回的对象没有方法或属性,因此您不能使用它的offset()value。要解决此问题,您需要分离返回的对象及其方法/属性并测试返回对象的有效性。

Private Sub ComboBox1_Change()
    If ComboBox1.Value = "" Then
        Label3.Caption = ""
    Else
        Dim fndrng As Range
        'Get just the find range
        Set fndrng = Worksheets("Currency").Cells.Find(UserForm1.ComboBox1.Value)
        'Make sure find found something
        If Not fndrng Is Nothing Then
            'use the methods/properties we want
            Label3.Caption = fndrng.Offset(0, -1).Value
        Else
            MsgBox "Selection not found", vbOKOnly, "Error"
        End If
    End If
End Sub

Private Sub UserForm_Initialize()
    ComboBox1.List = [Currency!C2:C168].Value
    Label3.Caption = ""
End Sub

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-06-01
    • 2014-04-02
    • 2021-05-22
    • 2021-10-11
    • 1970-01-01
    • 1970-01-01
    • 2011-12-14
    • 1970-01-01
    相关资源
    最近更新 更多