If and Then basic - excel

I am new to VBA and I want to test a basic If and Then Statement. I want to create a message to say Yes or No based on the data in cell A1 in excel named score. I had tried many things and sometimes just all the messages pop up so wondering how to write this properly?
Here is the actual statement:
Sub IfTest()
Dim Score As Integer
Dim Msgbox As String
Score = Cells(1, 1).Value
If Score = 1 Then
Msgbox = "Yes"
Else
Msgbox = "no"
End If
End Sub

Welcome to VBA!
MsgBox "This is my message", , "This is my Title"
Between the commas, you insert button styles.
Button styles and Title are optional.
So for your example, remove the "="'s and instead do:
If Score = 1 Then
Msgbox "Yes"
Else
Msgbox "no"
End If
Check out the MS link: MsgBox Function
* **EDIT per comintern's comment - remove this line !!!!!!
Dim Msgbox As String

Related

userform textbox required field-accept only a pattern of numbers

I need help trying to make an excel userform textbox to accept only a pattern of numbers. My pattern of numbers are 12 digits.00.4 digits or 8 digits so the textbox should only accept a number similar to 772344456566.00.0001 or 77186238.
I have searched for clues to similar issues but none give me any direction.
My current code is this but not close to my target goal:
Private Sub Textbox3_Exit(ByVal Cancel As MsForms.ReturnBoolean)
IF TextBox3.Value <>"" Or TextBox3.Value < 0 Then
MsgBox "Invalid sales order number"
TextBox3.SetFocus
End If
End Sub
Try this:
Private Sub Textbox3_Exit(ByVal Cancel As MsForms.ReturnBoolean)
If Not TextBox3.Value Like "########" Or _
Not TextBox3.Value Like "############.00.####" Then
MsgBox "Invalid sales order number"
TextBox3.SetFocus
End If
End Sub
and/or have a look at This. Basically, when used with the Like operator, # checks for any digit, so ## checks for a 2 digit number and so on.
Use the next function, please:
Function textOK(strText As String) As Boolean
If strText Like "############.00.####" Or strText Like "########" Then
textOK = True
End If
End Function
It can be used in your code in this way:
If textOK(TextBox3.Text) Then
'do whatever you need
Else
'send a warning message... or do something else.
End If
Edited:
You can test the above function in this relevant way:
Sub testTextOK()
Dim x As String
x = "123456787812.00.0014"
'x = "12345678"
'x = "123457j8"
'x = "123456789"
Debug.Print textOK(x)
'or use MsgBox and comment the above code line
MsgBox textOK(x)
End Sub
Please, un-comment from bottom to the top the x lines allocating values and see the return in Immediate Window (being in VBE: `Ctrl + G)...
Does it look now a little easier to understand how to use it?
Your code seems to be trying to reject values that are anything other than blank or negative.
Below is a selection of questions to review regarding validation of textbox forms in VBA.
Validating the format of a userform textbox entry
Validate textbox input
Making VBA Form TextBox accept Numbers only (including +, - and .)
Validating textbox entry on Userform (Excel VBA)
Userform entry validation
Firstly, check the length of the value. Then, just break the value into separate parts and check each of them. Something like this (cannot check it as on Linux now):
val = CStr(TextBox3.Value)
len_val = Len(val)
If len_val = 8 Then
If Not IsNumeric(val) Then
MsgBox "Error"
End If
ElseIf len_val = 20 Then
If (Not IsNumeric(CInt(Left(val, 12)))) Or _
Mid(val, 13, 4) <> ".00." Or _
(Not IsNumeric(CInt(Right(val, 4)))) Then
MsgBox "Error"
End If
Else
MsgBox "Error"
End If

Validate TextBoxes on a specific MultiPage page in an Excel UserForm

So I am trying to make sure that all TextBoxes are filled out. However, I only want this script to check a certain page on a MultiPage page on an Excel UserForm. Below is the code I'm using but it is checking every TextBox within the user form rather than the ones on the specific page. Also is a picture to show you. I have circled the Page named "Box" which is also Page 3 which I want to reference when validating the TextBoxes and the TextBoxes of which I would like to validate.
Snapshot of UserForm
Private Sub CommandButton2_Click()
Dim Ctrl As Control
Dim Answer1 As VbMsgBoxResult
' Checks to make sure data has been entered into all fields on the UserForm Page
For Each Ctrl In Me.Controls
If TypeOf Ctrl Is MSForms.TextBox Then
If Ctrl.Value = vbNullString Then
MsgBox "All fields must be completed before the information can be updated.", vbOkay + vbExclamation, "Missing Information"
Exit Sub
End If
End If
Next
' Displays box with Yes or No asking if they are sure they want to save and close document
Answer1 = MsgBox("Doing this will overwrite the previous data that was entered. Are you sure you want to do this?", vbYesNo + vbExclamation, "Update Cabinet Information")
' Writes the new data entered into the workbook
If Answer1 = vbYes Then
Sheet5.Range("B1").Value = TextBox1.Value
If IsDate(TextBox2.Value) Then
Sheet5.Range("B2").Value = Format(TextBox2.Value, "mm/dd/yyyy")
Else
MsgBox "One or more fields have an incorrect date format. Dates must be entered in this formay mm/dd/yyyy."
Exit Sub
End If
Sheet5.Range("B3").Value = TextBox3.Value
Sheet5.Range("G1").Value = TextBox4.Value
If IsDate(TextBox5.Value) Then
Sheet5.Range("G2").Value = Format(TextBox5.Value, "mm/dd/yyyy")
Else
MsgBox "One or more fields have an incorrect date format. Dates must be entered in this formay mm/dd/yyyy."
Exit Sub
End If
Sheet5.Range("G3").Value = TextBox6.Value
Sheet5.Range("J1").Value = TextBox7.Value
If IsDate(TextBox8.Value) Then
Sheet5.Range("J2").Value = Format(TextBox8.Value, "mm/dd/yyyy")
Else
MsgBox "One or more fields have an incorrect date format. Dates must be entered in this formay mm/dd/yyyy."
Exit Sub
End If
Sheet5.Range("J3").Value = TextBox9.Value
Sheet5.Range("M1").Value = TextBox10.Value
If IsDate(TextBox11.Value) Then
Sheet5.Range("M2").Value = Format(TextBox11.Value, "mm/dd/yyyy")
Else
MsgBox "One or more fields have an incorrect date format. Dates must be entered in this formay mm/dd/yyyy."
Exit Sub
End If
Sheet5.Range("M3").Value = TextBox12.Value
Sheet5.Range("P1").Value = TextBox13.Value
If IsDate(TextBox14.Value) Then
Sheet5.Range("P2").Value = Format(TextBox14.Value, "mm/dd/yyyy")
Else
MsgBox "One or more fields have an incorrect date format. Dates must be entered in this formay mm/dd/yyyy."
Exit Sub
End If
Sheet5.Range("P3").Value = TextBox15.Value
Sheet5.Range("S1").Value = TextBox16.Value
If IsDate(TextBox17.Value) Then
Sheet5.Range("S2").Value = Format(TextBox17.Value, "mm/dd/yyyy")
Else
MsgBox "One or more fields have an incorrect date format. Dates must be entered in this formay mm/dd/yyyy."
Exit Sub
End If
Sheet5.Range("S3").Value = TextBox18.Value
End If
End Sub
You'll need to refer to the Pages collection of the MultiPage object. Therefore, let's say that the multipage control is named MultiPage1, you'll need to amend the line as follows...
For Each Ctrl In Me.MultiPage1.Pages(2).Controls
Note that the index for the Pages collection is 0-based.

Compile Error with basic VBA Userform button (First VBA Project at college)

For a Spreadsheet task set by college, I have been asked to include a VBA user form into a student database spreadsheet. I have written a sub routine which enters the new student into a specific line within the worksheet (AddStudent) is there any obvious reason why Vba is not processing this function properly. The lines below show the code I have used.
Private Sub CommandButton1_Click()
If Me.txtStudent.Value = "" Or Me.txtBirth.Value = "" Or Me.txtFirstAdd.Value = "" Or Me.txtSecondAdd.Value = "" Or Me.txtTown.Value = "" Or Me.txtCounty = "" Or Me.txtPost.Value = "" Then MsgBox "Please fill in all details"
Else
Call AddStudent
End If
End Sub
This is my first VBA task and I am no programmer, so I apologise for what might appear to be a trivial question.(also I am having a little trouble with formatting as this is my first post of stack overflow)
When The Button is pressed I receive the following error message "compile error; Else without IF"
Thank you to anyone who may have the time to help me out here.
Put your MsgBox statement on a new line:
Private Sub CommandButton1_Click()
If Me.txtStudent.Value = "" Or Me.txtBirth.Value = "" Or Me.txtFirstAdd.Value = "" Or Me.txtSecondAdd.Value = "" Or Me.txtTown.Value = "" Or Me.txtCounty = "" Or Me.txtPost.Value = "" Then
MsgBox "Please fill in all details"
Else
Call AddStudent
End If
End Sub
The reasoning: VBA allows you to do If {condition} Then {Action} as a single statement, but when you construct your code this way, you can't have an Else clause. It's basically a way to shorthand:
If {condition} Then
{Action}
Else
'Do Nothing
End If
Also, if you have several OR conditions, you can improve legibility with a Case statement instead:
Private Sub CommandButton1_Click()
Select Case ""
Case Me.txtStudent.Value, Me.txtBirth.Value, Me.txtFirstAdd.Value, Me.txtSecondAdd.Value, Me.txtTown.Value, Me.txtCounty, Me.txtPost.Value
MsgBox "Please fill in all details"
Case Else
Call AddStudent
End Select
End Sub

How to detect if user select cancel InputBox VBA Excel

I have an input box asking user to enter a date. How do I let the program know to stop if the user click cancel or close the input dialog instead of press okay.
Something like
if str=vbCancel then exit sub
Currently, user can hit OK or Cancel but the program still runs
str = InputBox(Prompt:="Enter Date MM/DD/YYY", _
Title:="Date Confirmation", Default:=Date)
If the user clicks Cancel, a zero-length string is returned. You can't differentiate this from entering an empty string. You can however make your own custom InputBox class...
EDIT to properly differentiate between empty string and cancel, according to this answer.
Your example
Private Sub test()
Dim result As String
result = InputBox("Enter Date MM/DD/YYY", "Date Confirmation", Now)
If StrPtr(result) = 0 Then
MsgBox ("User canceled!")
ElseIf result = vbNullString Then
MsgBox ("User didn't enter anything!")
Else
MsgBox ("User entered " & result)
End If
End Sub
Would tell the user they canceled when they delete the default string, or they click cancel.
See http://msdn.microsoft.com/en-us/library/6z0ak68w(v=vs.90).aspx
Following example uses InputBox method to validate user entry to unhide sheets:
Important thing here is to use wrap InputBox variable inside StrPtr so it could be compared to '0' when user chose to click 'x' icon on the InputBox.
Sub unhidesheet()
Dim ws As Worksheet
Dim pw As String
pw = InputBox("Enter Password to Unhide Sheets:", "Unhide Data Sheets")
If StrPtr(pw) = 0 Then
Exit Sub
ElseIf pw = NullString Then
Exit Sub
ElseIf pw = 123456 Then
For Each ws In ThisWorkbook.Worksheets
ws.Visible = xlSheetVisible
Next
End If
End Sub
The solution above does not work in all InputBox-Cancel cases. Most notably, it does not work if you have to InputBox a Range.
For example, try the following InputBox for defining a custom range ('sRange', type:=8, requires Set + Application.InputBox) and you will get an error upon pressing Cancel:
Sub Cancel_Handler_WRONG()
Set sRange = Application.InputBox("Input custom range", _
"Cancel-press test", Selection.Address, Type:=8)
If StrPtr(sRange) = 0 Then 'I also tried with sRange.address and vbNullString
MsgBox ("Cancel pressed!")
Exit Sub
End If
MsgBox ("Your custom range is " & sRange.Address)
End Sub
The only thing that works, in this case, is an "On Error GoTo ErrorHandler" statement before the InputBox + ErrorHandler at the end:
Sub Cancel_Handler_OK()
On Error GoTo ErrorHandler
Set sRange = Application.InputBox("Input custom range", _
"Cancel-press test", Selection.Address, Type:=8)
MsgBox ("Your custom range is " & sRange.Address)
Exit Sub
ErrorHandler:
MsgBox ("Cancel pressed")
End Sub
So, the question is how to detect either an error or StrPtr()=0 with an If statement?
If your input box is an array, it does not work. I have solved it by adding a check for if it is an array first.
Dim MyArrayCheck As String
Dim MyPlateMapArray as variant
MyPlateMapArray = Application.InputBox("Select ....", Type:=8)
MyArrayCheck = IsArray(MyPlateMapArray)
If MyArrayCheck = "False" Then
Exit Sub
End If
I have solved it with a False like below
MyLLOQ = Application.InputBox("Type the LLOQ number...", Title:="LLOQ to be inserted in colored cells.", Type:=1)
If MyLLOQ = False Then Exit Sub
If user click cancel the sub will exit.
Another suggestion.
Create a message box when inputbox return null value. Example:
Dim PrC as string = MsgBox( _
"No data provided, do you want to cancel?", vbYesNo+vbQuestion, "Cancel?")
Sub TestInputBox()
Dim text As String
text = InputBox("Type some text")
If text = "" Then
MsgBox "button cancel pressed or nothing typed"
Else
MsgBox text
End If
End Sub
Inputbox send a boolean False value when Cancel is pressed.
contenidoy = Application.InputBox("Cantidad = ", titulox, contenidox, , , , , Type:=1)
'ESC or CANCEL
If contenidoy = False Then
MsgBox "Cancelado"
Else
MsgBox "EdiciĆ³n aceptada"
'End If

OptionButton determines value then use in macro

A basic simple VBA question that I havent been able to work out even though there are numerous tutorials about it.
I want a Userform to pop-up, give you two options (OptionButton1 and OptionButton2). You choose one, click ok. And depending on what Option is chosen a certain value is used (in an email, for which I DID finish the macro). For simplifying purposes i now just want the variable 'contents' to be printed in cell A1.
I have these parts so far:
Sub MailOption()
UserForm1.Show
End Sub
Private Sub OptionButton1_Click()
If OptionButton1.Value = True Then Var1 = "Text example 1"
End Sub
Private Sub OptionButton2_Click()
If OptionButton2.Value = True Then Var1 = "Text example 2"
End Sub
Private Sub SendEmail_Click()
Cells(1, 1).Value = Var1
End Sub
There are multiple problems: the variable is not shown in Cell A1 and when i press Send Email the Form is not closed. I am probably doing lots of stuff wrong but its the first time im using a userform. Ty very much
I would simply use this one without handling OptionButton_Click:
Private Sub SendEmail_Click()
Dim res As String
If OptionButton1.Value Then
res = "Text example 1"
ElseIf OptionButton2.Value Then
res = "Text example 2"
Else
res = "Nothing is selected"
End If
'write result in cell
ThisWorkbook.Worksheets("Sheet1").Range("A1").Value = res
'close form
Unload Me
End Sub

Resources