Pegasus Knight
Pegasus Knight

Reputation: 27

Unload Statement does NOT Unload UserForm

I'm sure this has a simple answer but it has me stumped. The following code is part of a user form I'm making in VBA. The form asks the user for the name of an item in one field, and the quantity of that item in another field. This code is part of what runs when the user clicks "okay" after entering that information. The If-Else Statement show below checks to see if the item (ItemName) appears on a sheet called Inventory. If it does not appear, then the user should see an error message, and the code should stop running. But, my code doesn't stop running. It seems to ignore that "Unload Me" line and keep right on going to the code after the If-Else Statement. What am I doing wrong here?

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

Upvotes: 1

Views: 5166

Answers (1)

ray
ray

Reputation: 8699

Exit Sub should get you the desired result:

    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

Upvotes: 2

Related Questions