VBA If statement to call Msgbox always calls msgbox - vba

I am trying to use an if statement to check for blanks and return a msgbox if there are blank fields. If there are no blank fields it runs another block of code. However even when you fill out all the fields the msgbox is always returned and the next block of code doesn't run. I'm pretty new to VBA and writing code in gneneral so any advice would be helpful.
Code in question:
'Check required fields
If IsEmpty(C3) Then
MsgBox ("Fill out all required fields")
ElseIf IsEmpty(C7) = True Then
MsgBox ("Fill out all required fields")
ElseIf IsEmpty(C9) = True Then
MsgBox ("Fill out all required fields")
ElseIf IsEmpty(C11) = True Then
MsgBox ("Fill out all required fields")
ElseIf IsEmpty(C13) = True Then
MsgBox ("Fill out all required fields")
ElseIf IsEmpty(C17) = True Then
MsgBox ("Fill out all required fields")
Else

You would reference a range like this:
If Len(Range("C3").Value) = 0 Then
MsgBox "Fill out all required fields"
But shorter to do something like this:
If Application.CountA(Range("C3,C7,C11,C13,C17")) < 5 Then
MsgBox "Fill out all required fields"
End if

C7 is not a Range. Nor are C9, C11, C13 or C17
[C7] is a range. A better way to write this, however, would be ActiveSheet.Range("C7") or ActiveSheet.Cells(7,3)
You can then do nifty things like use Error Handling and SpecialCells:
On Error GoTo NoErrors
Dim BlankFields AS Long
BlankFields = ActiveSheet.Range("C7,C9,C11,C13,C17").SpecialCells(xlCellTypeBlanks).Count
MsgBox "Fill out all required fields" & vbCrLf & BlankFields & "field(s) remaining"
NoErrors:
On Error GoTo 0

Related

Issue with checking for blank input boxes and sending appropriate message in VBA

I'm having an issue with my code in VBA properly checking for blank fields and giving the appropriate message in that event and I can't figure out what I've done wrong. My issue is that only the client name blank field checker actually works, the others do nothing at all. Here is a sample of my code.
'Error Handling
If (Me!ClientName) = "" Then
MsgBox "Client Name cannot be blank"
End
Else
If IsNumeric(ClientName.Value) = True Then
MsgBox "Client Name must be letters only."
End
Exit Sub
End If
End If
If (Me!ClientDoB) = "" Then
MsgBox "Client Date of Birth cannot be blank"
End
End If
If (Me!ClientAdd) = "" Then
MsgBox "Client Address cannot be blank"
End
End If
If (Me!ClientCity) = "" Then
MsgBox "Client City cannot be blank"
End
Else
If IsNumeric(ClientCity.Value) = True Then
MsgBox "Client City must be letters only."
End
Exit Sub
End If
End If
If (Me!ClientSt) = "" Then
MsgBox "Client State cannot be blank"
End
End If
If (Me!ClientZC) = "" Then
MsgBox "Client Zip Code cannot be blank"
End
Else
If IsNumeric(ClientZC.Value) = False Then
MsgBox "Client Zip Code must be numbers only."
End
Exit Sub
End If
End If
Consider using an if-elseif structure, such as:
If Me.clientname & "" = "" Then
MsgBox "Client Name cannot be blank"
ElseIf Me.clientname Like "*[!A-Za-z]*" Then
MsgBox "Client Name must contain letters only."
ElseIf Me.clientdob & "" = "" Then
MsgBox "Client Date of Birth cannot be blank"
ElseIf Me.clientadd & "" = "" Then
MsgBox "Client Address cannot be blank"
ElseIf Me.clientcity & "" = "" Then
MsgBox "Client City cannot be blank"
ElseIf Me.clientcity Like "*[!A-Za-z]*" Then
MsgBox "Client City must contain letters only."
ElseIf Me.clientst & "" = "" Then
MsgBox "Client State cannot be blank"
ElseIf Me.clientzc & "" = "" Then
MsgBox "Client Zip Code cannot be blank"
ElseIf Me.clientzc Like "*[!0-9]*" Then
MsgBox "Client Zip Code must be numbers only."
End If
This is because in MS Access a blank field is not necessarily a NULL. To get around this, use the NZ function instead. It is super helpful in situations like yours in which a field can be blank or NULL (MS Access differentiates between the two!!).
If (Nz(Me!ClientAdd,"")) = "" Then
MsgBox "Client Address cannot be blank"
End
End If
This will detect blanks AND nulls and provide you with your expected outcome as you describe.
The "If Then Else" solution post above is not recommended in your scenario. Because once it finds a "true" scenario all the other scenarios will be ignored...
The code you posted is the correct code (and method) to use. Simply wrap your fields with Nz(!yourfield, Value if Null) function.
Hope this helps.

VBA conditions for a UserForm

I am new on VBA. I want to put some restrictions on my inputs in the UserForm. I want My variable to be a number (the user should select the row Number) and if she/he put text or leave it blank an error message should appear. This is the code I have:
Public Sub AddPolicy_Click()
Dim RowNumber As Integer
RowNumber = TextBox1.Value
If RowNumber = "" Then
MsgBox "Error Row Number- enter a value!", vbOKCancel + vbCritical, "Error"
ElseIf VarType(RowNumber) = vbString Then
MsgBox "Error Row Number- enter a Numerical Value!", vbOKCancel + vbCritical, "Error"
End If
Range("A1") = RowNumber
End Sub
I know that the problem is because I declare my variable RowNumber as an Integer, But if I do not do that the software does not recognize my variable, and show me the error message for text, blank and number. SO I do not know how can I solve this.
Thank you in advance for your help
How about this?
Public Sub AddPolicy_Click()
Dim RowNumber As String
RowNumber = TextBox1.Value
If RowNumber = "" Then
MsgBox "Error Row Number- enter a value!", vbOKCancel + vbCritical, "Error"
ElseIf Not IsNumeric(RowNumber) Then
MsgBox "Error Row Number- enter a Numerical Value!", vbOKCancel + vbCritical, "Error"
End If
Range("A1") = RowNumber
End Sub
Edit: About the declaration of String, integer etc.: I know people tend to be very particular about this. But it really doesnt make a difference efficiency-wise for most macros. Here for example you wont gain anything by declaring it better. Even simply not dim'ing it would work nicely.
You could try this code.
The change event on the textbox will stop you being able to enter anything except numerics.
Private LastText As String '<-- place this at the very top of the module.
Private Sub TextBox1_Change()
With Me.TextBox1
'Allow only whole numbers.
If .Text Like "[!0-9]" Or Val(.Text) < -1 Or .Text Like "?*[!0-9]*" Then
.Text = LastText
Else
LastText = .Text
End If
End With
End Sub
Private Sub TextBox1_AfterUpdate()
'Remove any leading or trailing spaces
'(although the Change event should stop you entering spaces).
Me.TextBox1 = Trim(Me.TextBox1)
End Sub
Private Sub AddPolicy_Click()
With Me.TextBox1
If .Value <> "" Then
'Fully qualify where you want to put the data, or it will
'put it in A1 of whichever sheet happens to be active.
ThisWorkbook.Worksheets("Sheet1").Range("A1") = Me.TextBox1
Else
MsgBox "Invalid or no value entered.", vbCritical + vbOKOnly
End If
End With
End Sub

Multiple If Statements VBA

I'm very new to VBA and SQL, and I'm currently building a table to be uploaded to SQL onto Excel and using VBA.
I want to essentially say if column I(Check Market) or J(Check m2) have a value that says #NA then go no further and don't carry out the upload or the rest of the code. I think one of the problems might be I already have an IF loop - which is successful and has no errors associated with it.
This is my code so far
'Where Marked sht.Cells(Row,15) = "x" 'FIRST IF LOOP
If sht.Cells(lRow, 15) = "X" Then
'If I or J columns say #N/A then DO NOT continue
If IsError(sht.Cells(lRow, 9).Value) Then MsgBox "Error in Column 'Check Market'"
If IsError(sht.Cells(lRow, 10).Value) Then MsgBox "Error in Column 'Check m2'"
''''At the moment it is the above part that isn't successfully running, it notifies the user of an error but doesn't stop the process.
'Change blank spaces to be Null
*******
sSQL = *******Main part of code goes here******
'execute queries
********
'Put back all the 'null' values to blank
'''''
End If 'END OF IF X LOOP
I'm not clear if there's a possibility that both columns might have an error but I've provided for that just in case.
'If I or J say #N/A then dont proceed with upload.
If iserror(sht.Cells(lRow, 9).value) and iserror(sht.Cells(lRow, 10).value) Then
MsgBox "Errors in both Columns"
ElseIf iserror(sht.Cells(lRow, 9).value) Then
MsgBox "Error in Column 'Check Market'"
ElseIf iserror(sht.Cells(lRow, 10).value) Then
MsgBox "Error in Column 'Check KPI'"
Else: 'Continue
End if
Just adding to your original Code
I(9):Check Market J(10):Check m2
'If I or J say #N/A then dont proceed with upload.
If sht.Cells(lRow, 9).Value = "#N/A" Then
MsgBox "Error in Column 'Check Market'"
Exit Sub
ElseIf sht.Cells(lRow, 10).Value = "#N/A" Then
MsgBox "Error in Column 'Check KPI'"
Exit Sub
Else: 'Continue
Code for exiting with MsgBox
Dim response
response = MsgBox("My message here.", vbYesNo, "My Title")
If response = vbNo Then
Exit Sub
End If
MsgBox ("You clicked YES.")

MsgBox appears multiple times after data is pulled from a sheet

I'd like to get some help with the following code. I am very new to this but I think it's an easy solution I'm just unable to retrofit suggestions from other searches into my code.
The msgboxes are working fine on the first pass to check if the text box values are correct but when I am checking to see if a formula result from a sheet is correct I'm getting 5 message boxes popping up.
Hope this makes sense, let me know if you have any suggestions!
`Private Sub SpeedCommand_Click()
Dim ctl As Control
If TextBox1AM180.Value > 12000 And TextBox1AM180.Value <> "" Then
MsgBox "Rate Value is out of range for this boom. Ensure rate value is less than 12,000 lbs./acre", vbExclamation, "Main Bin Application Rate"
Me.TextBox1AM180.SetFocus
Exit Sub
End If
If (TextBox2AM180.Value > 120 Or TextBox2AM180.Value < 20) And TextBox2AM180.Value <> "" Then
MsgBox "Density Value is out of range. Ensure density value is between 20 and 120 lbs./cu ft.", vbExclamation, "Main Bin Density"
Me.TextBox2AM180.SetFocus
Exit Sub
End If
If TextBox3AM180.Value > 12000 And TextBox3AM180.Value <> "" Then
MsgBox "Rate Value is out of range for this boom. Ensure rate value is less than 12,000 lbs./acre", vbExclamation, "Granular Bin Application Rate"
Me.TextBox3AM180.SetFocus
Exit Sub
End If
If (TextBox4AM180.Value > 120 Or TextBox4AM180.Value < 20) And TextBox4AM180.Value <> "" Then
MsgBox "Density Value is out of range. Ensure density value is between 20 and 120 lbs./cu ft.", vbExclamation, "Granular Bin Density"
Me.TextBox4AM180.SetFocus
Exit Sub
End If
' Write data to worksheet
With Range("B4")
.Offset(0, 0).Value = Me.TextBox1AM180.Value
.Offset(1, 0).Value = Me.TextBox2AM180.Value
.Offset(5, 0).Value = Me.TextBox3AM180.Value
.Offset(6, 0).Value = Me.TextBox4AM180.Value
End With
If Range("MaxSpeed1").Value > 30 Then
MsgBox "Based upon rate and density, speed is restricted by machine top end application speed."
Exit Sub
End If
If Range("MaxSpeed2").Value > 30 Then
MsgBox "Based upon rate and density, speed is restricted by machine top end application speed."
Exit Sub
End If
' Hide the form
frmAirmax.Hide
Use the Application.EnableEvents property to temporarily disable events from firing and then re-enable them when you're done.
Something like this:
Application.EnableEvents = False
With Range("B4")
.Offset(0, 0).Value = Me.TextBox1AM180.Value
.Offset(1, 0).Value = Me.TextBox2AM180.Value
.Offset(5, 0).Value = Me.TextBox3AM180.Value
.Offset(6, 0).Value = Me.TextBox4AM180.Value
End With
Application.EnableEvents = True

Count if cell not blank

Hi All I have 2 formulas i'm trying to run but struggling to get the COUNTIF to calculate only if the cell isn't blank.
Sheets("Home").Select
If Range("A2:A14").Count = "13" Then
MsgBox "Current Load Full Please Complete & Export", vbCritical
Exit Sub
End If
2nd Code
Sheets("Home").Select
If Range("A2:A14").Count < "13" Then
MsgBox "Shipment is short do you want to continue?", vbCritical vbYesNo
Exit Sub
End If
On the 2nd code if vbYes then run code if vbNo then exit sub.
If you're trying to do some action depending on the condition "all cells in range A2:A14 are filled or not" - then this code might be the answer.
Sub check_count()
Sheets("Home").Select
Dim myRange As Range
Set myRange = Worksheets("Home").Range("A2:A14")
'using excel's built in function CountA to check count of non-blank cells
'if the count is 13 - then msgbox
If Application.WorksheetFunction.CountA(myRange) = 13 Then
MsgBox "Current Load Full Please Complete & Export", vbCritical
Exit Sub
'if the count is less then 13 - then do following
Else:
msg1 = MsgBox("Shipment is short do you want to continue?", vbYesNo)
If msg1 = vbYes Then
MsgBox "Enter missing products in A2:A14" 'you can run some code here as well
Else: Exit Sub
End If
End If
End Sub
Hope this answers your question.
In order to count all non-blank cells in a given range, you could use:
If ActiveSheet.Range("A2:A14").SpecialCells(xlCellTypeConstants).Count < 13 Then