OptionButton determines value then use in macro - excel

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

Related

VBA Multiple Textboxes Validation control

Dears,
I am preparing a simple userform to let a teacher to enter each student’s name and height in a class. There are two textboxes (textbox_name and textbox_height) and one “add to record” command button. I tried to make some validation control to prevent empty string to be entered. My validation control is in case textbox is empty, when the click the “add to record” button, the corresponding empty textbox turns pink; and when both textboxes are empty, both textboxes should turn pink, however only the first textbox turns pink in my below codes. Can you tell me why and how to correct it? Thanks.
Private Sub Cmd_addtorecord_Click()
If TextBox_Name = "" Then
TextBox_Name.BackColor = rgbPink
Exit Sub
End If
If TextBox_height = "" Then
TextBox_height.BackColor = rgbPink
Exit Sub
End If
'....
End sub
You can do it like this:
Private Sub Cmd_addtorecord_Click()
'ensure required fields have content
If FlagEmpty(Array(TextBox_Name, TextBox_height)) > 0 Then
MsgBox "One or more required values are missing", vbExclamation
Exit Sub
End If
'....
End Sub
'check required textboxes for content, and flag if empty
' return number of empty textboxes
Function FlagEmpty(arrControls) As Long
Dim i As Long, numEmpty As Long, clr As Long
For i = LBound(arrControls) To UBound(arrControls)
With arrControls(i)
clr = IIf(Len(Trim(.Value)) > 0, vbWhite, rgbPink)
.BackColor = clr
If clr = rngpink Then numEmpty = numEmpty + 1
End With
Loop
FlagEmpty = numEmpty
End Function
You're Exiting the sub before you get to the second textbox. Change your code to something like this:
Private Sub Cmd_addtorecord_Click()
If TextBox_Name = "" or TextBox_height = "" Then
If TextBox_Name = "" Then
TextBox_Name.BackColor = rgbPink
End If
If TextBox_height = "" Then
TextBox_height.BackColor = rgbPink
End If
Exit Sub
End If
'....
End sub

After user input, and I have autofilled 2 other textboxes, how do I stop my macro from running a search on the other boxes?

I have 3 textboxes, of which when you input data into any one of the textboxes, the other 2 will populate.
the codes are very long, so I've just added what it does at every line of code
Private Sub tbAC_AfterUpdate()
'Declarations
textbox 1 = tbAC
textbox 2 = tbAN
textbox 3 = tbIC
If tbAC is Nothing Then
tbAC = ""
Elseif tbAC.TextLength > 0 Then
'Find tbAC in column AGC
Set MCodef = wsa.Columns(AGC).Find(what:=tbAC, LookIn:=xlValues, Lookat:=xlPart)
If MCodef is Nothing Then
Msgbox ("Invalid Code")
Else
Mcoder = Mcodef.Row
tbAN = wsa.Range(AGN & Mcoder).Value
tbIC = wsa.Range(AIC & Mcoder).Value
End if
End If
End Sub
'It's pretty much the same if you fill in tbAN or tbIC
Private Sub tbAN_AfterUpdate()
End Sub
Private Sub tbIC_AfterUpdate()
End Sub
Given that user input in tbAN, I only want excel to run the sub tbAN_AfterUpdate and not the others. Any help would be appreciated, thanks in advance!
If you have code that is triggered by entering data into the text box, but don't want that code to execute when using an alternate function in VBA, you can use:
Application.EnableEvents = False
So if you are entering into TextBox1 and want to update TextBox2 when you enter into TextBox1, put this into TextBox1's Code. You would use this when the code is first initialized, but you need to remember to reverse that at the end of the code or prior to the code terminating (e.g. through Exit Sub or some other forced command) as once EnableEvents = False, no code will trigger without setting it to:
Application.EnableEvents = True

ComboBox Value Changes

Private Sub Workbook_open()
With Sheet1.ComboBox1
.AddItem "Soccer"
.AddItem "Tennis"
End With
End Sub
I would like to make an if statement such that if the ComboBox1 value changes either from nothing to Soccer/tennis or from one item to another
then
Range("A1").Value = "This learner Plays Sport"
the problem is I don't know how to do the part where the combobox value changes either from nothing to Soccer/tennis or from one item to another
I have tried workbook.change and it gives me an error the closes the whole program.
Instead of workbook change event try the ComboBox change event like this:
Private Sub ComboBox1_Change()
If Sheet1.ComboBox1.Value = "Soccer" Or Sheet1.ComboBox1.Value = "Tennis" Then
Worksheets("Sheet1").Range("A1").Value = "This learner Plays Sport"
End If
End Sub
To get to this change event just double click the combobox from the Worksheet and it will open the VBA editor for you.
This only tells you what the newly selected value is. If you need to know what it was before the change it will be a bit more complicated. You'll need to create a variable to store/track the value to compare against once changed.
If you end up with a long list of sports, I'd suggest using Select Case instead of if statements. For example:
Private Sub ComboBox1_Change()
Select Case Sheet1.ComboBox1.Value
Case "Soccer", "Tennis"
Worksheets("Sheet1").Range("A1").Value = "This learner Plays Sports"
Case "Lacross"
Worksheets("Sheet1").Range("A1").Value = "Something Different"
Case Else
Debug.Print "value not in list"
End Select
End Sub

Userform Textbox to work like an html textbox

I am trying to figure out how to get a textbox in an excel userform to update like an HTML textbox. For instance, if you have a default value set to "First Name" and you click in that textbox, it will disappear and let you type in. Once you click out, if you didn't type anything, it will go back to the default "First Name".
I have found quite a few asking about this same type of thing, but none are working for me. Here is my code so far.
Sub QCToolsForm()
QCTools.Show vbModeless
End Sub
Private Sub RUBSTotalExpense_Enter()
Debug.Print "Enter"
If Me.RUBSTotalExpense.Value = "Total Expense" Then
Me.RUBSTotalExpense.Value = ""
End If
End Sub
Private Sub RUBSTotalExpense_Exit(ByVal Cancel As MSForms.ReturnBoolean)
Debug.Print "Exit"
If Me.RUBSTotalExpense.Value = "" Then
Me.RUBSTotalExpense.Value = "Total Expense"
End If
End Sub
Private Sub UserForm_Initialize()
updateDefault
End Sub
Public Function updateDefault()
If Me.RUBSTotalExpense.Value = "" Then
Me.RUBSTotalExpense.Value = "Total Expense"
End If
End Function
The exit sub is not running until I close the userform. I have also tried lose and getfocus with no luck with those at all. I have also tried before and afterupdate, but they only work the first time. I want it to disappear every time you click in the box if the value is "Total Expense". How do I get the exit sub or something similar to run when I leave the textbox?
I tried using your code for Enter and Exit and it worked for me with a test userform. It's updating the field correctly, and printing "Enter" when you select the textbox and "Exit" when you select something else on the userform. Note that for Exit to trigger you need to give focus to something else on the userform. Simply clicking elsewhere will not take focus from the textbox, you must click on another textbox or other control.
I suggest using Debug.Print to observe exactly when each method you try is being called, so that you can be sure when your code is running.
Private Sub TextBox1_Enter()
Debug.Print "Enter"
If TextBox1.Value = "Total Expense" Then
TextBox1.Value = ""
End If
End Sub
Private Sub TextBox1_Exit(ByVal Cancel As MSForms.ReturnBoolean)
Debug.Print "Exit"
If TextBox1.Value = "" Then
TextBox1.Value = "Total Expense"
End If
End Sub

VBA Text Box displaying Currency

I have a form with a number of text boxes for user input (this is in a User Form not on the spreadsheet). I have a few boxes that are related to currency and I need them to show the comma and decimal point as the user enters their criteria into the box. So far I have found a bunch of the same formulas online but when I input my number into the box it goes with 4.00 (if i hit 4 first) and all i can change after that is the second 0. Here is something similar I see online:
textbox1 = format(textbox1, "$#,##0.00")
Also seen some with cDbl
No matter what I try it won't let me enter anything more than the first number I enter. I need help. Thanks!
Formatting as the user types in data gets very tricky. May be better to format after the entry is complete.
Entry can also be validated and old value restored if entry deemed invalid
Dim TextBox1oldValue As String
Private Sub TextBox1_AfterUpdate()
If IsNumeric(TextBox1) Then
TextBox1 = Format(TextBox1, "$#,##0.00")
Else
TextBox1 = TextBox1oldValue
End If
End Sub
Private Sub TextBox1_BeforeUpdate(ByVal Cancel As MSForms.ReturnBoolean)
If IsNumeric(TextBox1) Then
TextBox1oldValue = Format(TextBox1, "$#,##0.00")
End If
End Sub
Private Sub UserForm_Initialize()
TextBox1oldValue = "$0.00"
TextBox1 = "$0.00"
End Sub
You need to use the TextBox Change event, like:
Private Sub TextBox1_Change()
If TextBox1 = vbNullString Then Exit Sub
If IsNumeric(TextBox1) Then CurrencyTransform(TextBox1)
End Sub
You then create the CurrencyTransform function to modify what it shows in the TextBox.
Try simply this...
Private sub textbox1_AfterUpdate()
textbox1 = format(textbox1, "$#,##0.00")
end sub
I wrote this inspired by chris' solution. It works while user is typing!
Private waiting As Boolean
Private Sub TextBox1_Change()
If waiting Then Exit Sub
waiting = True
TextBox1 = formatAsCurrency(TextBox1)
waiting = False
End Sub
Private Function formatAsCurrency(v As String)
If v = "" Then
formatAsCurrency = Format(0, "0.00")
Else
Dim vv As Variant
vv = Replace(v, ",", "")
vv = Replace(vv, ".", "")
formatAsCurrency = Format(vv / 100, "#,##0.00")
End If
End Function
Try this:
Private Sub TextBox1_Change()
TextBox1.Value = Format(TextBox1.Value, "$#,##0.00")
End Sub
This worked for me just fine, so it should help you as well.
If you want to do calculations that involve multiple text boxes, don't use .value after the name of the text box. Instead, use val( before the name of the text box while following it with an end parenthesis. I used .value and got weird results. Instead of, for example, $100 for TextBox1.Value + TextBox2.Value where TextBox1.Valueis equal to $25 and TextBox2.Value is equal to $75, I would get "$25$75".

Resources