Search code examples
excelvbauserform

Ensure combobox and textbox on a userform are not blank


I would like to ensure that a combobox and textbox are not empty. If empty, prompt to ensure that it is not left blank.

I tried a loop

Private Sub submitactive_click()
    Sheets("ComplaintsData").Activate
    Sheets("ComplaintsData").Unprotect

    emptyRow = WorksheetFunction.CountA(Range("A:A")) + 1

    If (cmbRegion.Value = "") Then
        MsgBox "Need to select Region"
    End If
    If (tbObjLink.Value = "") Then
        MsgBox "Need to enter Objective Link"
    End If
    Exit Sub

    Cells(emptyRow, 2).Value = emptyRow - 1

    Cells(emptyRow, 1).Value = dtdate.Value
    Cells(emptyRow, 3).Value = cmbChannel.Value
    Cells(emptyRow, 4).Value = cmbIssue.Value
    Cells(emptyRow, 5).Value = cmbSource.Value
    Cells(emptyRow, 6).Value = tbname.Value
    Cells(emptyRow, 7).Value = ccdemail.Value
    Cells(emptyRow, 8).Value = ccdphone.Value
    Cells(emptyRow, 9).Value = cmbRegion.Value
    Cells(emptyRow, 10).Value = cmbBusinessGroup.Value
    Cells(emptyRow, 11).Value = cmbBusinessUnit.Value
    Cells(emptyRow, 12).Value = tbreferredby.Value
    Cells(emptyRow, 13).Value = tbaction.Value
    Cells(emptyRow, 14).Value = tbnotes.Value
    Cells(emptyRow, 15).Value = tbObjLink.Value
    Cells(emptyRow, 16).Formula = "=TEXT(A" & emptyRow & ", ""mmm     yyyy"")"

    MsgBox "Complaints Information Submitted"

    Sheets("Forms").Activate

    Sheets("ComplaintsData").Protect AllowFiltering:=True
    ActiveWorkbook.Save

    Call UserForm_Initialize

    End Sub

The code will not submit the form however when I enter data in the blank fields the sub no longer works.


Solution

  • That's because you have Exit Sub in the wrong place. When your code runs, it checks whether either control is empty. If either one is empty, a message is display, and then it simply exits the sub, regardless of whether one or both are empty. Try something like this...

    If (cmbRegion.Value = "") Then
        MsgBox "Need to select Region"
        Exit Sub
    End If
    
    If (tbObjLink.Value = "") Then
        MsgBox "Need to enter Objective Link"
        Exit Sub
    End If