I'd be grateful if someone could look at this code and let me know if you could see why it is that when I run it, Excel crashes and then reopens:
Any suggestions gratefully received
Code:
Sub btnAddNewCustomer_Click()
If ValidateMandatoryFields() Then
AddNewCustomer
Unload Me
End If
End Sub
Private Function ValidateMandatoryFields() As Boolean
If Trim(Me.txtNewCustomer.Value) = "" Or _
Trim(Me.txtNewAddress1.Value) = "" Or _
Trim(Me.txtNewAddress2.Value) = "" Or _
Trim(Me.txtNewEmail.Value) = "" Or _
Trim(Me.txtNewPhone.Value) = "" Or _
Trim(Me.txtNewContactName.Value) = "" Then
MsgBox "Please complete all mandatory fields.", vbExclamation, "Missing Information"
ValidateMandatoryFields = False
Else
ValidateMandatoryFields = True
End If
End Function
Sub AddNewCustomer()
Dim ws As Worksheet
Dim tbl As ListObject
Dim newRow As ListRow
Dim response As VbMsgBoxResult
On Error GoTo ErrHandler
Set ws = ThisWorkbook.Sheets("Customers")
Set tbl = ws.ListObjects("Customer_List")
Set newRow = tbl.ListRows.Add
newRow.Range.Cells(1, tbl.ListColumns("Customer Name").Index).Value = Me.txtNewCustomer.Value
newRow.Range.Cells(1, tbl.ListColumns("Address 1").Index).Value = Me.txtNewAddress1.Value
newRow.Range.Cells(1, tbl.ListColumns("Address 2").Index).Value = Me.txtNewAddress2.Value
newRow.Range.Cells(1, tbl.ListColumns("Email").Index).Value = Me.txtNewEmail.Value
newRow.Range.Cells(1, tbl.ListColumns("Phone").Index).Value = Me.txtNewPhone.Value
newRow.Range.Cells(1, tbl.ListColumns("Contact Name").Index).Value = Me.txtNewContactName.Value
newRow.Range.Cells(1, tbl.ListColumns("Project").Index).Value = Me.txtNewProject.Value
response = MsgBox("Do you wish to add more Customers?", vbQuestion + vbYesNo)
If response = vbYes Then
Me.txtNewCustomer.Value = ""
Me.txtNewAddress1.Value = ""
Me.txtNewAddress2.Value = ""
Me.txtNewEmail.Value = ""
Me.txtNewPhone.Value = ""
Me.txtNewContactName.Value = ""
Me.txtNewProject.Value = ""
ElseIf response = vbNo Then
Unload Me
End If
Exit Sub
ErrHandler:
MsgBox "An error occurred: " & Err.Description, vbExclamation, "Error"
End Sub
Any suggestions gratefully received