Step by Step With Error Handling Code
Step by Step With Error Handling Code
1. Open Excel.
2. Press Alt + F11 to open the VBA Editor.
3. In the VBA Editor, go to Insert → UserForm. A blank UserForm will appear.
You will add various elements like text boxes, labels, and buttons.
1. Add Labels:
o From the toolbox, select the Label control and place it on the UserForm.
o Create the following labels:
Label for "Guest Name:"
Label for "Room Type:"
Label for "Number of Nights:"
Label for "Check-in Date:"
2. Add TextBoxes and ComboBox:
o Add a TextBox for "Guest Name" and set the Name property to txtGuestName.
o Add a ComboBox for "Room Type" and set the Name property to cmbRoomType.
In the ComboBox, add the following room types in the RowSource
property: Single, Double, Suite.
o Add a TextBox for "Number of Nights" and set the Name property to txtNights.
o Add a TextBox for "Check-in Date" and set the Name property to txtCheckIn.
3. Add Buttons:
o Add a CommandButton for "Submit" and set the Caption to Submit. Set the
Name property to btnSubmit.
o Add another CommandButton for "Cancel" and set the Caption to Cancel. Set
the Name property to btnCancel.
Final Layout
4 Labels (for Guest Name, Room Type, Number of Nights, and Check-in Date)
3 TextBoxes (for Guest Name, Number of Nights, and Check-in Date)
1 ComboBox (for Room Type)
2 CommandButtons (Submit and Cancel)
vba
Copy code
Private Sub btnSubmit_Click()
On Error GoTo ErrorHandler
ErrorHandler:
MsgBox "An error occurred: " & Err.Description, vbCritical, "Error"
End Sub
vba
Copy code
Private Sub btnCancel_Click()
txtGuestName.Value = ""
cmbRoomType.Value = ""
txtNights.Value = ""
txtCheckIn.Value = ""
End Sub
This code clears the form fields when the "Cancel" button is clicked.
1. Go back to the VBA Editor and click Insert → Module. This will add a blank module.
2. Add this code to display the UserForm:
vba
Copy code
Sub ShowBookingForm()
BookingForm.Show
End Sub
3. Return to Excel.
4. Press Alt + F8, select ShowBookingForm, and click Run. The UserForm should appear.
5. Test the UserForm:
o Try leaving fields blank to see the error messages.
o Enter valid data to successfully submit the form.
o Use the "Cancel" button to clear the form.