如何避免VBA Userform Combobox输入异常时触发运行时错误?
VBA组合框输入容错处理方案
报错的核心原因是Find方法没有匹配到结果时会返回Nothing,此时直接访问.Offset属性就会触发「Object variable not set」运行时错误,只需先对Find返回结果做非空判断即可解决。
方案1:输入无效时自动重置为空
Private Sub ComboBox1_Change() Dim findRng As Range If ComboBox1.Value = "" Then Label3.Caption = "" Else ' 接收Find方法返回结果,添加LookAt参数实现严格完全匹配 Set findRng = Worksheets("Currency").Cells.Find(UserForm1.ComboBox1.Value, LookAt:=xlWhole) If findRng Is Nothing Then ' 未匹配到内容则清空组合框输入 ComboBox1.Value = "" Else Label3.Caption = findRng.Offset(0, -1).Value End If End If End Sub Private Sub UserForm_Initialize() ComboBox1.List = [Currency!C2:C168].Value Label3.Caption = "" End Sub
方案2:输入无效时弹出错误提示
Private Sub ComboBox1_Change() Dim findRng As Range If ComboBox1.Value = "" Then Label3.Caption = "" Else Set findRng = Worksheets("Currency").Cells.Find(UserForm1.ComboBox1.Value, LookAt:=xlWhole) If findRng Is Nothing Then ' 弹出无效输入提示 MsgBox "Invalid Input", vbExclamation ' 如需同时清空输入可取消注释下行代码 ' ComboBox1.Value = "" Else Label3.Caption = findRng.Offset(0, -1).Value End If End If End Sub Private Sub UserForm_Initialize() ComboBox1.List = [Currency!C2:C168].Value Label3.Caption = "" End Sub
内容的提问来源于stack exchange,提问作者Drawleeh
相关产品推荐
相关产品推荐

