Home » excel » excel – How do I ignore no user input?

excel – How do I ignore no user input?

Posted by: admin May 14, 2020 Leave a comment

Questions:

My code is supposed to check each column “C” cell for whatever input is in TextBox2 then, if found, using the row found in adjust the Column “D” intersected cell contents to “IN”.

All this is happening as desired with one exception. If I click the command button “Check IN” with no input in textbox2, it sets the first next empty cell in column “D” as “IN”.

Private Sub CheckIn_Click()

Dim FoundRange As Range
Dim Status As Range
    Set FoundRange = Columns("C").Find(What:=TextBox2.Text, LookIn:=xlValues, LookAt:=xlWhole, MatchCase:=False)

    If Not FoundRange Is Nothing Then
    Set Status = FoundRange.Offset(ColumnOffset:=1)
       Status.Value = "IN"
       TextBox2 = ""
       ThisWorkbook.Save
    Else
        Status.Value = ""
        TextBox2 = ""
        TextBox1.SetFocus
        MsgBox "Not Found"
    End If

End Sub

What I attempted to do is use the same script from line 9 at line 13 but with an empty value so that even if something is done the cell is empty. On the other hand, after running the code without TextBox2 input I received this error:“Object variable or With block variable not set” at line 13.

I do not understand what variable is not being set. All I am trying to do is mitigate what happens if the button is hit with no input.

How to&Answers:

Test First:

Private Sub CheckIn_Click()

    Dim FoundRange As Range
    Dim Status As Range

    If TextBox2.Text = "" Then
        MsgBox "Test Skipped"
    Else
        Set FoundRange = Columns("C").Find(What:=TextBox2.Text, LookIn:=xlValues, LookAt:=xlWhole, MatchCase:=False)

        If Not FoundRange Is Nothing Then
           Set Status = FoundRange.Offset(ColumnOffset:=1)
           Status.Value = "IN"
           TextBox2 = ""
           ThisWorkbook.Save
        Else
            Status.Value = ""
            TextBox2 = ""
            TextBox1.SetFocus
            MsgBox "Not Found"
        End If
    End If

End Sub

Answer:

First check the value of TextBox2, then proceed if there is a value.

Private Sub CheckIn_Click()

    If TextBox2.Value <> "" Then 

        Dim FoundRange As Range
        Dim Status As Range
        Set FoundRange = Columns("C").Find(What:=TextBox2.Text, LookIn:=xlValues, LookAt:=xlWhole, MatchCase:=False)

        If Not FoundRange Is Nothing Then
            Set Status = FoundRange.Offset(ColumnOffset:=1)
            Status.Value = "IN"
            TextBox2.Value = ""
        Else
            MsgBox "Not Found"
        End If

    End If

End Sub