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
Related
I made a coding about calculation, there are 2 numbers in the 2 different 2 boxes, when I calculate the answer is wrong, there is a msgbox shown "Try again", if correct, the msgbox shown "you are correct", but is insert nothing or words then press enter, it will be shown error.
I want if the inputbox insert nothing then press enter, the inputbox will be shown again to restrick someone insert something into the inputbox and can not insert any words into the inputbox, if insert any words, also the inputbox will be shown again return to empty.
Does anyone can tell me how to solve this problem?
Thank you so much.
Dim a As String
Do While True
a = InputBox("Please enter your answer")
If a = Val(txtnumber1.Text) + Val(txtnumber2.Text) Then
Exit Do
Else
MsgBox("Try again!!!!")
End If
Loop
MsgBox("You are correct!")
End Sub
End Class
Dim a As String
Do While True
Do While a="" Or Not IsNumeric(a)
a = InputBox("Please enter your answer")
Done
If val(a) = Val(txtnumber1.Text) + Val(txtnumber2.Text) Then
Exit Do
Else
MsgBox("Try again!!!!")
End If
Loop
MsgBox("You are correct!")
InputBox in Do...Loop
Sub QnA()
Const Title As String = "Q&A"
Dim Answer As String
Dim TryAgain As Long
Do
Answer = InputBox("Please enter your answer", Title, "")
If Len(Answer) = 0 Then
MsgBox "Nothing entered.", vbExclamation, Title
Exit Sub
End If
If IsNumeric(Answer) Then
If Val(Answer) = Val(txtnumber1.Text) + Val(txtnumber2.Text) Then
Exit Do
End If
End If
TryAgain = MsgBox("Wrong answer (""" & Answer & """). Try again?", _
vbYesNo + vbQuestion, Title)
If TryAgain = vbNo Then Exit Sub
Loop
MsgBox "You are correct!", vbInformation, Title
End Sub
I have a userform which will ask for a number that is then getting looked up in a spreadsheet, saving that range in a variable. When it's found the number, it will hide the first userform and bring up the second one, but in order for me to proceed with the update, I will need to use the same range that I've previously set against my variable in userform1, any idea how to do that? I have declared it as a Public variable but it still doesn't work. Code as it follows:
UserForm1:
Public FillRange As Range
Public BKref As Variant
Private Sub CommandButton1_Click()
On Error GoTo errhndlr:
Set FillRange = Sheets("Loader").Cells.Find(TextRef.Value).Offset(0, 2)
BKref = TextRef.Value
If Not FillRange = "" Then
UserForm1.Hide
UserForm2.Show
Exit Sub
ElseIf FillRange = "" Then
MsgBox "Booking Reference cannot be empty!", vbCritical, "Error: No Booking Ref."
UserForm1.Hide
Exit Sub
Else
MsgBox "Unexpected error, please re-start and try again. If you had this message more than 2 times, please update the line manually.", vbCritical, "Error"
UserForm1.Hide
Exit Sub
End If
Exit Sub
errhndlr:
MsgBox "Booking reference not found, please double-check that the booking reference you've entered is correct, alternatively update it manually.", vbCritical, "Error"
UserFrom1.Hide
End Sub
UserForm2:
Private Sub CommandButton1_Click()
FillRange = TextPloaded.Value
FillRange.Offset(0, 2) = TextTime.Value
FillRange.Offset(0, 3) = TextLoader.Value
If Not TextComm.Value = "" Then
FillRange.Offset(0, 4) = TextComm.Value
ElseIf TextComm.Value = "" Then
FillRange.Offset(0, 4) = ""
End If
If Not FillRange = FillRange(0, -1) Then
MsgBox "Actual and Planned pallets doesn't match, please highlight the diescrepancies on the assembly sheet!"
BKref = FillRange.Offset(0, -2)
Sheets("Assembly").Activate
Sheets("Assembly").Rows(1).AutoFilter Field:=16, Criteria1:=BKref
UserForm2.Hide
Else
UserForm2.Hide
UserForm1.Show
End If
End Sub
If you make use of Option Explicit in every module/userform etc. This forces you to declare all variables properly and shows a message if a variable is not declared.
The issue is that if you declare Public FillRange As Range in Userform1 the variable is only valid in Userform1 but not in Userform2.
So I recommend to decare the variable in a Module instead of Userform1. This way it is accessible everywhere.
Alternative
You can access a public Userform1 variable in Userfrom2 by Userform1.FillRange
Add a property in your first form:
Property Get FillRange() As Range
Set FillRange = Range("A1")
End Property
And read it from your second form:
Dim FillRange
Set FillRange = UserForm1.FillRange
I create combo box selection using userform in Excel macro.
What I want to do is, to prevent the user to click OK without selecting a value.
Here is my code, I don't know what is wrong, the message box doesn't show.
Private Sub UserForm_Initialize()
ComboBox1.RowSource = "Sheet1!G1:G" & Range("G" & Rows.Count).End(xlUp).Row
ComboBox2.RowSource = "Sheet1!G1:G" & Range("G" & Rows.Count).End(xlUp).Row
End Sub
Private Sub CommandButton1_Click()
If IsNull(ComboBox1) Then
MsgBox ("ComboBox Has Data")
End If
Workbooks("Select Project.xlsm").Sheets("Sheet1").Range("B2").Value = ComboBox1.Value
Workbooks("Select Project.xlsm").Sheets("Sheet1").Range("C2").Value = ComboBox2.Value
End Sub
Can anybody help what is wrong with my code? Sorry, I'm new to VBA.
You're not checking the Text property of your ComboBox. You should process like this.
Private Sub CommandButton1_Click()
If (ComboBox1.Text = "") Then
MsgBox "ComboBox Has No Data"
Exit Sub
End If
Workbooks("Select Project.xlsm").Sheets("Sheet1").Range("B2").Value = ComboBox1.Value
Workbooks("Select Project.xlsm").Sheets("Sheet1").Range("C2").Value = ComboBox2.Value
End Sub
What changed ?
I changed If IsNull(ComboBox1) Then with If (ComboBox1.Text = "") Then so this will check the Text property in your ComboBox.
I also added Exit Sub to leave the function if the ComboBox is empty so it doesn't commit the operation after.
IsNull(ComboBox1) and IsNull(ComboBox1).Value will both never be true. Null is a value returned from a database if a field contains no value. You have to check if the value of the ComboBox is empty. An empty string in VBA is a string with the length 0, so you have to use on of those:
If Me.ComboBox1 = "" then ...
If Me.ComboBox1.Value = "" then ...
If Me.ComboBox1.Text = "" then ...
(For the difference between value and text-property see Distinction between using .text and .value in VBA Access)
Anyhow, I would go for the solution to enable/disable the button (as Rosetta suggested). Put a event-routine to the Combobox:
Private Sub ComboBox1_Change()
Me.CommandButton1.Enabled = Me.ComboBox1.Value <> ""
End Sub
this is my first post, please be patient if I'm doing/asking something wrong.
My issue is:
I got 2 columns, A is number of children, B is name of those children.
Those values are manually entered, I simply would like to have B mandatory if A is filled.
Here is what I thought:
Private Sub Workbook_BeforeClose(Cancel As Boolean)
If Not IsEmpty(Sheet1.Range("A1")) Then
If IsEmpty(Sheet1.Range("B1")) Then
MsgBox "Please fill in cell B1 before closing."
Cancel = True
Else '
End If
End If
End Sub
This is actually working perfectly, unfortunately I can't manage to extend it for whole columns, when replacing A1 with A1:A1000 and B1 with B1:B1000 for instance,it doesn't work.
How can I validate this for both entire column A and B?
thanks in advance!
Try this
Private Sub Workbook_BeforeClose(Cancel As Boolean)
Cancel = Evaluate("SUMPRODUCT(--(ISBLANK(Sheet1!B:B) <> ISBLANK(Sheet1!A:A)))")
If Cancel Then MsgBox "Please fill in column B before closing."
End Sub
EDIT
In order to take the user to the place where data is missing, and taking into account the additional information you provided about your data, try this:
'Private Sub Workbook_BeforeClose(Cancel As Boolean)
Private Sub Workbook_BeforeSave(ByVal SaveAsUI As Boolean, Cancel As Boolean)
Dim r: r = Evaluate( _
"MATCH(FALSE, ISBLANK('ELENCO AGGIORNATO'!V:V) = ISBLANK('ELENCO AGGIORNATO'!W:W), 0)")
If IsError(r) Then Exit Sub ' All is fine
Cancel = True
Application.Goto Sheets("ELENCO AGGIORNATO").Cells(r, "V").Resize(, 2)
msgBox "Please fill missing data before saving."
End Sub
Also note that I recommend Workbook_BeforeSave instead of Workbook_BeforeClose, because there's no harm if the user decides to drop his (incomplete) work and close the workbook without saving.
You may try something like this...
Private Sub Workbook_BeforeClose(Cancel As Boolean)
Dim str As String
Dim Rng As Range, Cell As Range
Dim FoundBlank As Boolean
Set Rng = Sheet1.Range("A1:A1000")
str = "Please fill the cells listed below before colsing..." & vbNewLine & vbNewLine
For Each Cell In Rng
If Cell <> "" And Cell.Offset(0, 1) = "" Then
FoundBlank = True
str = str & Cell.Address(0, 1) & vbNewLine
End If
Next Cell
If FoundBlank Then
Cancel = True
MsgBox str, vbExclamation, "List of Blank Cells Found!"
End If
End Sub
I'm trying to get a value that user inputs manually as an integer and I have to take into account the fact that user might not enter an integer. That's why I'm trying to catch a type mismatch error. However, when I enter an integer value I still get type mismatch error.
This is the piece of code that makes this error.
Dim number As Integer
On Error GoTo error
number = InputBox("Enter an integer:")
error:
MsgBox ("Input error. Make sure you enter an integer value.")
Exit Sub
The Application.InputBox Method allows you to specify what the Type of data returned.
MSDN Application.InputBox Method (Excel)
Sub Example1()
Dim number As Integer
number = Application.InputBox(Prompt:="Enter an integer:", Type:=1)
End Sub
Because Application.InputBox with the Type 1 parameter will return 0 if the user cancels, I would prefer to use a standard InputBox. The way to use it is to have a separate variable capture the value and test that the return value meets your criteria. In this way, you can avoid any errors.
Sub Example2()
Dim number As Integer
Dim result As String
result = InputBox("Enter an integer:")
If result = "" Then
MsgBox "Good Bye", vbInformation, "Action Cancelled"
Exit Sub
ElseIf IsNumeric(result) Then
If CDbl(result) > CInt(result) Then
MsgBox "You entered a Decimal" & vbCrLf & "Try Again", vbInformation, "Intergers Only"
Else
number = result
End If
Else
MsgBox "Intergers Only" & vbCrLf & "Try Again", vbInformation, "Intergers Only"
End If
End Sub
Here is one way:
Dim number As Integer
On Error Resume Next
number = InputBox("Enter an integer:")
If Err.number <> 0 Then
MsgBox ("Input error. Make sure you enter an integer value.")
Exit Sub
End If
On Error GoTo 0
Note though that this will accept non-integer number entries; it's not clear if that's a concern.