Search code examples
excelvbaif-statementuserform

Excel Userform - check if cell is empty then


I'm trying to make a userform where after someone clicks the button, it first checks that specified cells are empty.

If they already have values in them then I want to display a message box to the user. If they are empty then I'll proceed to fill them in. For some reason whenever I run the userform, it displays the message box that the cells are not empty but then continues to fill them in anyways. I'm not sure if I'm using the if statement incorrectly or something.

here's the code starting after i've declared the variable (BtwCells) from the userform text box inputs:

If IsEmpty(BtwCells.Value) = False Then

MsgBox ("Error - overlapping reservations")

End If

BtwCells.Interior.ColorIndex = 6
BtwCells.Value = Application.username & "/" & Me.TBNotes.Value
End Sub

Solution

  • Based on your code as is - there is a logical error with your If...Then Statement.

    The statement is executed and whether your MsgBox displays or not, the code will continue to:

    BtwCells.Interior.ColorIndex = 6
    BtwCells.Value = Application.username & "/" & Me.TBNotes.Value
    

    You need to tell the code within the If...Then block to Exit Sub which will abort the code and prevent anything below that line from executing.

    If IsEmpty(BtwCells.Value) = False Then
    
        MsgBox ("Error - overlapping reservations")
        Exit Sub  'This will abort the code below this line from executing.
    
    End If
    
    BtwCells.Interior.ColorIndex = 6
    BtwCells.Value = Application.username & "/" & Me.TBNotes.Value
    End Sub