如何避免用户窗体组合框运行时错误?
How do I avoid Userform Combobox runtime error?
希望是一个简单的问题。我有一些在 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
但是当您输入不属于声明的组合框范围的内容时,它会引发运行时错误 'Object variable not set'。我如何愚弄此组合框,以及当进行任何不属于选择范围的不规则条目时,它会恢复为“”空?或者弹出一个错误框,提示“输入无效”?
如果 Find
找不到任何东西,它 returns 一个空对象。返回的对象没有方法或属性,因此您不能使用它的 offset()
或 value
。要解决此问题,您需要分离返回的对象及其 methods/properties 并测试返回对象的有效性。
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
希望是一个简单的问题。我有一些在 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
但是当您输入不属于声明的组合框范围的内容时,它会引发运行时错误 'Object variable not set'。我如何愚弄此组合框,以及当进行任何不属于选择范围的不规则条目时,它会恢复为“”空?或者弹出一个错误框,提示“输入无效”?
如果 Find
找不到任何东西,它 returns 一个空对象。返回的对象没有方法或属性,因此您不能使用它的 offset()
或 value
。要解决此问题,您需要分离返回的对象及其 methods/properties 并测试返回对象的有效性。
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