Message box for null fields - vba

I am trying to create a database for part locations. Three of the fields (JobNumber, PartNumber and Location) are required fields and I have an If statement written to check for Nulls and error handling to give a message box. After the message box is closed, it will let me return to the form but it will not allow me to edit the field again AND it still adds the incomplete data to the table. Any advice?
Private Sub cmdAddNew_Click()
If IsNull(Me.JobNumber) Then
GoTo cmdAddNew_Click_Err
ElseIf IsNull(Me.PartNumber) Then
GoTo cmdAddNew_Click_Err
ElseIf IsNull(Me.Location) Then
GoTo cmdAddNew_Click_Err
End If
On Error GoTo cmdAddNew_Click_Err
On Error Resume Next
DoCmd.GoToRecord , "", acNewRec
If (MacroError <> 0) Then
Beep
MsgBox MacroError.Description, vbOKOnly, ""
End If
cmdAddNew_Click_Exit:
Exit Sub
cmdAddNew_Click_Err:
MsgBox "Job Number, Part Number and Location are required."
End Sub

Adding Cancel = True in your second if statement should fix this.
Private Sub cmdAddNew_Click()
If IsNull(Me.JobNumber) Then
GoTo cmdAddNew_Click_Err
ElseIf IsNull(Me.PartNumber) Then
GoTo cmdAddNew_Click_Err
ElseIf IsNull(Me.Location) Then
GoTo cmdAddNew_Click_Err
End If
On Error GoTo cmdAddNew_Click_Err
On Error Resume Next
DoCmd.GoToRecord , "", acNewRec
If (MacroError <> 0) Then
Beep
MsgBox MacroError.Description, vbOKOnly, ""
Cancel = True
End If
cmdAddNew_Click_Exit:
Exit Sub
cmdAddNew_Click_Err:
MsgBox "Job Number, Part Number and Location are required."
End Sub
Alternatively, you could define functions to check for a null value and return a boolean result:
Function isvalid(Field as string) As Boolean
If IsNull(field)
isvalid = False
Else
isvalid = True
End If
End Function
Sub Check_valid()
Call isvalid(field 1)
Call isvalid(f2)
Call isvalid(f3)
If isvalid(field 1) = false Or isvalid(f2) = false Or isvalid(f3) = false Then
msgbox "Job Number, Part Number and Location are required."
Exit Sub
End If
End Sub
Hope this helps!

Related

Excel VBA Forms Error Message loop

i currently have a problem with a simple login form in excel (VBA), when having an error, continuing and having another error it still gives me two more MsgBoxes with errors but with the "Unload Me" and "Goto Ende" it should close itself completely.
Any guesses why this isn't working? I know this is very basic and probably very redundant, but it should still work.
Public Name As Variant
Public Password As Variant
Private Sub Btn_Register_Cancel_Click()
Unload Me
End Sub
Private Sub Btn_Register_Register_Click()
Start:
Dim Error As Integer
Error = 0
Name = Tbx_Register_Name.Value
Password = Tbx_Register_Password.Value
'Check for Name, Password, Password2 if empty
If Tbx_Register_Name.Value = "" Then
Error = MsgBox("Please enter a username.", _
vbRetryCancel, "Error")
If Error = 2 Then
Unload Me
GoTo Ende
Else
Application.ScreenUpdating = False
Register.Hide
Register.Show
Application.ScreenUpdating = True
GoTo Start
End If
ElseIf Tbx_Register_Password.Value = "" Then
Error = MsgBox("Please enter a password.", _
vbRetryCancel, "Error")
If Error = 2 Then
Unload Me
GoTo Ende
Else
Application.ScreenUpdating = False
Register.Hide
Register.Show
Application.ScreenUpdating = True
GoTo Start
End If
ElseIf Tbx_Register_Password2.Value = "" Then
Error = MsgBox("This field cannot be empty.", _
vbRetryCancel, "Error")
If Error = 2 Then
Unload Me
GoTo Ende
Else
Application.ScreenUpdating = False
Register.Hide
Register.Show
Application.ScreenUpdating = True
GoTo Start
End If
End If
With Workbooks("General Makro.xlsx").Worksheets("User")
'Check for Username match in registration list
For i = 1 To 100
If .Cells(i, 1).Value = Name Then
Error = MsgBox("This username is already taken.", _
vbRetryCancel, "Error")
If Error = 2 Then
Unload Me
i = 100
GoTo Ende
Else
Application.ScreenUpdating = False
Register.Hide
Register.Show
Application.ScreenUpdating = True
GoTo Start
End If
End If
Next i
End With
'Check for the passwords to match
If Tbx_Register_Password.Value = Tbx_Register_Password2.Value Then
With Workbooks("General Makro.xlsx").Worksheets("User")
For i = 1 To 100
If .Cells(i, 1) = "" Then
.Cells(i, 1).Value = Name
.Cells(i, 2).Value = Password
Tbx_Register_Password.Value = ""
Tbx_Register_Password2.Value = ""
Application.ScreenUpdating = False
Register.Hide
Login.Show
Tbx_Login_Name.Value = .Cells(i, 1).Value
Tbx_Login_Password.Value = .Cells(i, 2).Value
Application.ScreenUpdating = True
i = 100
GoTo Ende
End If
Next i
End With
Else
Error = MsgBox("The passwords have to match!", vbRetryCancel, "Error")
If Error = 2 Then
Unload Me
GoTo Ende
Else
Application.ScreenUpdating = False
Register.Hide
Register.Show
Application.ScreenUpdating = True
GoTo Start
End If
End If
Ende:
End Sub
Edit: I Actually Tried to do the 2nd UserForm for the login, and i happen to get the same problem there. Everything works just fine, until i close the whole program, then the error-message appears again. Am i unloading the userform incorrect? Maby the login userform says open and continues when everything is getting closed.
Edit 2: I could just turn off alerts but that would be an ugly solution and definitely nothing i want to implement on every close button in the program.
You can verify blank values in textboxes with this:
If TextBox.Text = "" Then
MsgBox "Is blank!"
Unload Me
GoTo Ende
End If
'Your code
Ende: Exit Sub
To verify the username and password in a database, you can do this:
Dim sh As Worksheet
Dim LastRow As Long
Dim UserRange As Range
Dim UserMatch As Range
Set sh = ThisWorkbook.Sheets("database")
LastRow = sh.Range("A" & Rows.Count).End(xlUp).Row
Set UserRange = sh.Range("A1:A" & LastRow)
Set UserMatch = UserRange.Find(What:=UserTextBox.Text, LookIn:=xlValues)
If Not UserMatch Is Nothing Then
MsgBox "User exists!"
If PwdTextBox.Text = UserMatch.Offset(0, 1) Then
MsgBox "Pwd matched!"
'do something
Else
MsgBox "Wrong password!"
'do something
End If
Else
MsgBox "User dont exists!"
'do something
End If
This will work if in the database the usernames are in column A and the passwords in column B.

Error Checking CheckBoxes

I have 6 CheckBoxes right now under an Audience category and want to make it so that they have to select at least 1 of the 6 CheckBoxes or an error message saying "Please select an Audience" will appear.
Right now with the code below, the project will still be entered regardless of if they check one of the 6 boxes or not.
My current code looks like:
Function CheckInputs() As Boolean
If Not CheckControl(Me.nameTextbox, "Please enter your name") Then Exit Function
If Not CheckControl(Me.projectTextbox, "Please enter a Project Name") Then Exit Function
If Not CheckControl(Me.initiativeCombobox, "Please select an Initiative") Then Exit Function
If Not CheckControl(Me.impactCombobox, "Please select Impact Type") Then Exit Function
If Not CheckControl(Me.lengthListbox, "") Then If Not CheckControl(Me.lengthListbox2, "Please enter project length") Then Exit Function
If Not CheckControl(Me.rvpCheckbox, "") Then If Not CheckControl(Me.umCheckbox, "") Then If Not CheckControl(Me.uwCheckbox, "") Then If Not CheckControl(Me.baCheckbox, "") Then If Not CheckControl(Me.uaCheckbox, "") Then If Not CheckControl(Me.otherCheckbox, "Please select an Audience") Then Exit Function
CheckInputs = True
End Function
Private Function CountSelectedListBoxItems(lb As MSForms.ListBox) As Long
Dim i As Long
With lb
For i = 0 To .ListCount - 1
If .Selected(i) Then CountSelectedListBoxItems = CountSelectedListBoxItems + 1
Next i
End With
End Function
Function CheckControl(ctrl As MSForms.Control, errMsg As String) As Boolean
Select Case TypeName(ctrl)
Case "TextBox"
CheckControl = Trim(ctrl.Value) <> ""
Case "ComboBox"
CheckControl = ctrl.ListIndex <> -1
Case "ListBox"
CheckControl = CountSelectedListBoxItems(ctrl) > 0
Case "CheckBox"
CheckControl = ctrl.Value = False
' Case Else
End Select
If errMsg = "" Then Exit Function
If CheckControl Then Exit Function
ctrl.SetFocus
MsgBox errMsg
End Function
Would setting a CheckControl function for CheckBox as ctrl.Value = False be the appropriate route? Or did I not set my CheckInputs function correctly?
Yes, it seems to me that (if I understand correctly) your CheckInputs function is currently incorrect.
The following line of code:
If Not CheckControl(Me.rvpCheckbox, "") Then If Not CheckControl(Me.umCheckbox, "") Then If Not CheckControl(Me.uwCheckbox, "") Then If Not CheckControl(Me.baCheckbox, "") Then If Not CheckControl(Me.uaCheckbox, "") Then If Not CheckControl(Me.otherCheckbox, "Please select an Audience") Then Exit Function
needs to be change to the following:
If UserForm1.rvpCheckbox.Value = False And _
UserForm1.umCheckbox.Value = False And _
UserForm1.uwCheckbox.Value = False And _
UserForm1.baCheckbox.Value = False And _
UserForm1.uaCheckbox.Value = False And _
UserForm1.otherCheckbox.Value = False Then
UserForm1.otherCheckbox.Caption = "Please select an Audience"
'...or maybe a message box instead?
MsgBox "Please select an Audience"
Exit Function
End If

Error Checking Two Possibilities

My current code is checking for either lengthListbox or lengthListbox2 to have a selection or it will display an error message. What's the easiest way to make it so it is a selection from either lengthListbox or lengthListbox2 or the message "Please enter project length" will be displayed?
Function CheckInputs() As Boolean
If Not CheckControl(Me.nameTextbox, "Please enter your name") Then Exit Function
If Not CheckControl(Me.projectTextbox, "Please enter a Project Name") Then Exit Function
If Not CheckControl(Me.audienceCombobox, "Please select an Audience") Then Exit Function
If Not CheckControl(Me.impactCombobox, "Please select Impact Type") Then Exit Function
If Not CheckControl(Me.lengthListbox, "Please select a current year month") Then Exit Function
If Not CheckControl(Me.lengthListbox2, "Please select a next year month") Then Exit Function
CheckInputs = True
End Function
Private Function CountSelectedListBoxItems(lb As MSForms.ListBox) As Long
Dim i As Long
With lb
For i = 0 To .ListCount - 1
If .Selected(i) Then CountSelectedListBoxItems = CountSelectedListBoxItems + 1
Next i
End With
End Function
Function CheckControl(ctrl As MSForms.Control, errMsg As String) As Boolean
Select Case TypeName(ctrl)
Case "TextBox"
CheckControl = Trim(ctrl.Value) <> ""
Case "ComboBox"
CheckControl = ctrl.ListIndex <> -1
Case "ListBox"
CheckControl = CountSelectedListBoxItems(ctrl) > 0
' Case Else
End Select
If CheckControl Then Exit Function
ctrl.SetFocus
MsgBox errMsg
End Function
Some things I've tried:
Trying to enter an error check in the enter button
Private Sub enterButton_Click()
If Me.lengthListbox.ListIndex = -1 And Me.lengthListbox2.ListIndex = -1 Then
MsgBox "Please enter Project Length"
End If
If Not CheckInputs Then Exit Sub 'check for fields to have values
Process GetWs(Me.impactCombobox.Value) ' process data passing the proper worksheet got from GetWs() function
MsgBox "Project Entered Successfully"
ClearUFData 'clear the data
End Sub
I've also tried making a separate subfunction that is meant for checking listboxes only but couldn't make it work within CheckInputs
try two functions little modifications:
1) nest the listboxes checks (see last line before CheckInputs = True)
Function CheckInputs() As Boolean
If Not CheckControl(Me.nameTextbox, "Please enter your name") Then Exit Function
If Not CheckControl(Me.projectTextbox, "Please enter a Project Name") Then Exit Function
If Not CheckControl(Me.audienceCombobox, "Please select an Audience") Then Exit Function
If Not CheckControl(Me.impactCombobox, "Please select Impact Type") Then Exit Function
If Not CheckControl(Me.lengthListbox, "") Then If Not CheckControl(Me.lengthListbox2, "Please enter project length") Then Exit Function
CheckInputs = True
End Function
so that the first listbox possible negative check will have the second listbox check decide about the "exit"
2) slightly modify CheckControl (see first line right after End Select)
Function CheckControl(ctrl As msforms.Control, errMsg As String) As Boolean
Select Case TypeName(ctrl)
Case "TextBox"
CheckControl = Trim(ctrl.Value) <> ""
Case "ComboBox"
CheckControl = ctrl.ListIndex <> -1
Case "ListBox"
CheckControl = CountSelectedListBoxItems(ctrl) > 0
' Case Else
End Select
If errMsg = "" Then Exit Function
If CheckControl Then Exit Function
ctrl.SetFocus
MsgBox errMsg
End Function
so that no action is taken if the passed error message string is a void one

Error message box select statement to handle yes or no

need help with the yes no portion of the error message, if yes I want the code to be launched again and if no then exit sub.
Public Sub Reset()
Dim pt As PivotTable
Dim slice As Slicer
Application.ScreenUpdating = False
ActiveWorkbook.Model.Refresh
For Each pt In ActiveSheet.PivotTables
pt.RefreshTable
For Each slice In pt.Slicers
slice.SlicerCache.ClearAllFilters
On Error GoTo 0
Next slice
pt.PivotCache.Refresh
Next pt
Error 0:
MsgBox "Sorry, Missing data, do you wish to continue?", _
vbCritical vbYesNo, "Restart process!"
Select Case vbYesNo
Case yes
MergeMultipleSheets
Case Else
Exit Sub
End Select
Application.ScreenUpdating = True
End Sub
Here is yes no portion of your code (assuming that you want to launch module MergeMultipleSheets if yes button is clicked):
Sub Reset()
Dim xlAns As Integer
xlAns = MsgBox("Sorry, Missing data, do you wish to continue?", vbYesNo, "Restart process!")
Select Case xlAns
Case vbYes
' do something
' if You want to call sub MergeMultipleSheets
MergeMultipleSheets
Case Else
' do something
Exit Sub
End Select
End Sub
Quick Example
Sub MsgBx()
Dim xlMsgBox As Integer
Dim Cancel As Boolean
xlMsgBox = MsgBox("Do you want to do this ", vbYesNoCancel)
If xlMsgBox = vbCancel Then
Cancel = True ' Exit
Exit Sub
ElseIf xlMsgBox = vbYes Then
' do something
ElseIf xlMsgBox = vbNo Then
' do something
End If
End Sub

Vlookup with VBA

I am trying to do an automated vlookupfunction but I am getting a run time error:
1004 "Unable to get the Vlookup property of the worksheet functionclass"
Would need some help on where it could have gone wrong and how it could be adjusted!
This is the code:
Sub FINDSAL()
'On Error GoTo MyErrorHandler:
Dim Seat_No As String
Seat_No = InputBox("Enter the Seat Number:")
If Len(Seat_No) > 0 Then
nameit = Application.WorksheetFunction.Vlookup(Seat_No, Sheets("L12 - Data Sheet").Range("B4:E250"), 2, False)
MsgBox "The name is : $ " & nameit
Else
MsgBox ("You entered an invalid value")
End If
Exit Sub
MyErrorHandler:
If Err.Number = 1004 Then
MsgBox "Employee Not Present in the table."
End If
End Sub
Sub FINDSAL()
On Error GoTo MyErrorHandler:
Dim Seat_No As Integer
Seat_No = InputBox("Enter the Seat Number:")
If Len(Seat_No) > 0 Then
nameit = Application.WorksheetFunction.Vlookup(Seat_No, Sheets("L12 - Data Sheet").Range("B4:E250"), 2, False)
MsgBox "The name is : $ " & nameit
Else
MsgBox ("You entered an invalid value")
End If
Exit Sub
MyErrorHandler:
If Err.Number = 1004 Then
MsgBox "Employee Not Present in the table."
End If
End Sub