Excel VBA Dynamically refer to UserForm TextBox and get value - excel

lets say in a UserForm I have two textboxes, TextBox1 and TextBox2.
How can I dynamically refer to and get the values of these TextBoxes?
Depending on the value of a TextBox, certain other actions should be triggered.
However, I can only make it work, if I explicitly name the TextBoxes and cannot figure out, how to do it dynamically. Can anybody help me?
This works:
If TextBox1.Value > 0 Then
Do something
End If
If TextBox2.Value > 0 Then
Do something
End If
Since there are actually more than 2 TextBoxes, I imagined doing something like this but it does not work:
Dim i as Integer
For i = 1 to 2
If ("TextBox" & i).Value > 0 Then
Do something
End if
Next i
So I guess my question is, how can I combine a string (one part of the name of the TextBox, with a variable (here i) to get another variable (?) which represents the TextBoxes and from which the value can be read? Or is there another/better solution to my problem?
Kind regards

Related

Hide rows based on variable in Textfield of Userform

i'm wondering if someone could help me with a little issue.
I have a textbox in an userform where people can add numbers for example 3. I need an macro when a checkbox is on then a few rows needs to be hidden. For example total range is B3 to B50 and if people typ 3 in the textbox B3 + 3rows needs to be visibele and the rest needs to be hidden.
Sub CommandButton1_Click()
If UserForm12.CheckBox2.Value = True Then
Rows("[B4+Karel]:B55").Hidden = True
End Sub
Could some one help me to fix this?
if people typ 3 in the textbox B3 + 3rows needs to be visibele and the rest needs to be hidden.
First hide all rows in the range and then show only the relevant rows. I am assuming that the name of the textbox is TextBox1. Change as applicable.
Is this what you are trying? (Untested). Also I have not done any error handling. I am sure you can take care of that?
Rows("3:50").Hidden = True
Rows("3:" & 3 + Val(TextBox1.Text)).Hidden = False
Note: When you are hiding/showing rows, you do not need the column names. You can directly work with row numbers as shown above.

Excel VBA Get adjacent userform control value

I have a userform with several rows of textboxes. As I loop through the controls, I'm concatenating the textbox values for a final string. Rather than looping through every textbox, I am only looping through the first textbox in the row and trying to assign a value to a variable with the replace method.
What I've tried: TBvalue = Replace(ctl.Name, "Textbox1", "Textbox2")
followed by
TBvalue2 = OnboardingLogForm.TBvalue.value
Also tried: TBvalue = OnboardingLogForm.Textbox & i.value when iterating with i
How can I get the values of other textboxes without statically referring to them?
Found an answer. Thanks for your help.
Me.Controls("TextBox" & i).value
Or, if there's any number order to your control names, you can try:
For Each ctl In Userform1.MultiPage1.Pages(0).Controls
blah = Me.Controls(Replace(ctl.Name, "TextBox1", "TextBox2")).value
Next

Create a VBA Message Box Based on Cell Value

So, this should be fairly easy to implement, but I am unable to get the message box to display.
Context - this is for an estimation tool - if the user enters a value for a particular cell that is less than a minimum threshold, I want to bring up a message box to let them know that's not a valid entry.
The cell I am referring to is named (let's just say TEST). Its location is on the UI tab (1 of 4 tabs in the workbook) is row 47, column 17.
Here is the code I have tried so far:
Sub UI Alerts()
If Cells(47, 17) < "1000" Then
MsgBox ("Minimum Value is 1000")
Exit Sub
End If
Similarly, with the named cell
Sub UI Alerts()
If ("TEST").value < "1000" Then
MsgBox ("Minimum Value is 1000")
Exit Sub
End If
I have set this up in the VBA module that corresponds to the UI tab, so I shouldn't have to reference the sheet. Any idea why the message box isn't displaying? Is it possible to automatically display a message box based on a cell value?
Thanks.
Unless there is a specific reason we need this to be a macro, it sounds like standard data validation would work for you here. Try this: select the cell you want the rules applied to, then on the ribbon/toolbar find Data > Data Validation. You can require a whole number greater than 1,000 (or a value in another cell), display a comment box with instructions when the user selects the cell, and an error message if an invalid number is entered.
You need to use the Change event within the worksheet. Below is a sample code that should work with your named range. At any rate, it should show you how to do so.
Private Sub Worksheet_Change(ByVal Target As Range)
If Target.Address = Range("TEST").Address Then
If Range("TEST").Value < 1000 Then
MsgBox ("Minimum Value is 1000")
End If
End If
End Sub
You need to add your code to the Worksheet "Change" event.
Right now, you have code but it never gets called.

Can a text box in a UserForm contain formula?

I have had a look online for an answer to this but no joy with coming across one as of yet. Is it possible to have a text box in a UserForm be dynamic?
My current idea is to have 3 columns of text boxes, in Column 1 & 2 the user need to enter there data and was wondering if in Column 3 there is a way to show the value involving Column 1 and Column 2?
If this isn't possible, are you able to reference a cell on a sheet and then get the useform to display the cells value?
Ideally i would like this to be possible as it provides the user with a quick check to ensure they've entered the data right.
Edit 1
TextBox18.Value = (TextBox1.Value + TextBox10.Value) / 2
I found that this line of code allowed me to reference two text boxes dynamically but textbox 18 concatenating rather than added the numbers. Is there a way round this?
Thanks
Alternatively something like this could help, this will add the values and not concatenate them:
TextBox3.Value = (Val(TextBox1.Value) + Val(TextBox2.Value))
Use the TextBox_Change() event method to dynamically update values.
Example:
Sub TextBox46_Change()
TextBox46.Value=(TextBox1.Value + TextBox36.Value) / 2
End Sub

Writing an input integer into a cell

I am writing a quick application myself - first project, however I am trying to find the VBA code for writing the result of an input string to a named cell in Excel.
For example, a input box asks the question "Which job number would you like to add to the list?"... the user would then enter a reference number such as "FX1234356". The macro then needs to write that information into a cell, which I can then use to finish the macro (basically a search in some data).
You can use the Range object in VBA to set the value of a named cell, just like any other cell.
Range("C1").Value = Inputbox("Which job number would you like to add to the list?)
Where "C1" is the name of the cell you want to update.
My Excel VBA is a little bit old and crusty, so there may be a better way to do this in newer versions of Excel.
I recommend always using a named range (as you have suggested you are doing) because if any columns or rows are added or deleted, the name reference will update, whereas if you hard code the cell reference (eg "H1" as suggested in one of the responses) in VBA, then it will not update and will point to the wrong cell.
So
Range("RefNo") = InputBox("....")
is safer than
Range("H1") = InputBox("....")
You can set the value of several cells, too.
Range("Results").Resize(10,3) = arrResults()
where arrResults is an array of at least 10 rows & 3 columns (and can be any type). If you use this, put this
Option Base 1
at the top of the VBA module, otherwise VBA will assume the array starts at 0 and put a blank first row and column in the sheet. This line makes all arrays start at 1 as a default (which may be abnormal in most languages but works well with spreadsheets).
When asking a user for a response to put into a cell using the InputBox method, there are usually three things that can happen¹.
The user types something in and clicks OK. This is what you expect to happen and you will receive input back that can be returned directly to a cell or a declared variable.
The user clicks Cancel, presses Esc or clicks × (Close). The return value is a boolean False. This should be accounted for.
The user does not type anything in but clicks OK regardless. The return value is a zero-length string.
If you are putting the return value into a cell, your own logic stream will dictate what you want to do about the latter two scenarios. You may want to clear the cell or you may want to leave the cell contents alone. Here is how to handle the various outcomes with a variant type variable and a Select Case statement.
Dim returnVal As Variant
returnVal = InputBox(Prompt:="Type a value:", Title:="Test Data")
'if the user clicked Cancel, Close or Esc the False
'is translated to the variant as a vbNullString
Select Case True
Case Len(returnVal) = 0
'no value but user clicked OK - clear the target cell
Range("A2").ClearContents
Case Else
'returned a value with OK, save it
Range("A2") = returnVal
End Select
¹ There is a fourth scenario when a specific type of InputBox method is used. An InputBox can return a formula, cell range error or array. Those are special cases and requires using very specific syntax options. See the supplied link for more.
I've done this kind of thing with a form that contains a TextBox.
So if you wanted to put this in say cell H1, then use:
ActiveSheet.Range("H1").Value = txtBoxName.Text

Resources