我确信这有一个简单的答案,但它让我难过。以下代码是我在VBA中创建的用户表单的一部分。表单要求用户在一个字段中输入项目的名称,并在另一个字段中询问该项目的数量。此代码是用户在输入该信息后单击“okay”时运行的代码的一部分。下面显示的If-Else语句检查项目(ItemName)是否出现在名为Inventory的工作表上。如果没有出现,则用户应该看到错误消息,代码应该停止运行。但是,我的代码并没有停止运行。它似乎忽略了“卸载我”行,并在If-Else语句之后继续执行代码。我在这里做错了什么?
Private Sub cmdOkay_Click()
Dim Quantity As Double
Dim ItemName as String
Dim FoundRange As Range
ItemName = Item_Name_Field
Quantity = Quantity_Field
Sheets("Inventory").Select
Range("A1").Select
Set FoundRange = Cells.Find(What:=ItemName, After:=ActiveCell, LookIn:=xlFormulas, LookAt:=xlWhole, SearchOrder:=xlByColumns, SearchDirection:=xlNext, MatchCase:=False, SearchFormat:=False)
If FoundRange Is Nothing Then
Dim AlertBox As Double
AlertBox = MsgBox(ItemName & " was not found in Inventory. Check your spelling and try again.", vbExclamation, "Item Not Found")
Unload Me
Else
'....
'(more code)
End If
'(more code)
End Sub
答案 0 :(得分:2)
退出子可以获得所需的结果:
Dim AlertBox As Double
AlertBox = MsgBox(ItemName & " was not found in Inventory. Check your spelling and try again.", vbExclamation, "Item Not Found")
Unload Me
Exit Sub