Excel VBA Course
Excel VBA Course - From Beginner to Expert

200+ Video Lessons
50+ Hours of Video
200+ Excel Guides

Become a master of VBA and Macros in Excel and learn how to automate all of your tasks in Excel with this online course. (No VBA experience required.)

View Course

VBA - Mandatory cells in a form and clear form

0

I have created an input form to get data and store it in another tab in excel using a macro as per the instructions on this site. I now need to make a field mandatory before the data is submitted. e.g. a message box pops up when you hit submit if a cell is blank. 

And also, i need the vba to clear the whole form to restart inputting new data. 

Answer
Discuss

Answers

0
Selected Answer

Assuming that your Submit button is called CommandButton1 you might use the code below.

Private Sub CommandButton1_Click()

    If TextBox3.Value = "" Then
        MsgBox "You must enter your age.", _
               vbExclamation, "Mandatory field"
        TextBox3.SetFocus
    Else
        ' take the action associated with "Submit" here
        ClearForm
        TextBox1.SetFocus
    End If
End Sub

Private Sub ClearForm()

    ' list all your textboxes here by name
    Const Controls As String = "TextBox1,TextBox2,TextBox3"
    Dim Ctl() As String
    Dim i As Integer

    Ctl = Split(Controls, ",")
    For i = 0 To UBound(Ctl)
        Me.Controls(Ctl(i)).Value = ""
    Next i
End Sub

This code runs when the button is pressed. It first checks if TextBox3 was filled. If it wasn't filled a message box pops up telling the user to fill and that field and the focus is set on that field at the same time. You can extend this to check several controls, one after the other, and give a different message to each (or the same).

If no exceptions are found the data are submitted to processing and, thereafter, the form is cleared and the focus set back to the first one.

Discuss
0

To clear a cell do something like this:

Range("A1").value = ""

Put this line as many times as you need, one for each field. A1 is the cell reference for the input field in the worksheet.

To tell the user to input something if they didn't, you should use the Data Validation methods that are shown in the Idiot Proof Forms course, the videos you are talking about, or you can use an IF statement with a message box, something like this:

if range("A1").value = "" then
msgbox"You must fill-out the entire form."
else
' Your code to save the input data here
end if

You will basically surround your current code with an IF statement like the one I wrote above.

Code here was typed out by hand so it will look a little different once you input and capitalizations and such are added by the VBA window.

Discuss


Answer the Question

You must create an account to use the forum. Create an Account or Login