How to get value from textbox in excel. I have 3 textbox, TextBox 1, TextBox 2, TextBox 3. How to SUM all three textbox to cell "A4". When I update textbox, the cell "A4" is change.
Bear in mind that text boxes contain text (strings), even in their Value property. Therefore their value must be converted to a number when summing up and the resulting number must be converted to text when it's assigned to TextBox4. Most of this VBA will do automatically most of the time. If you want your program to work correctly all the time you should consider giving instructions. The following code will create a value that can be assigned to a variable of Double data type.
Dim MySum As Double
MySum = Val(TextBox1.Value) + Val(TextBox2.Value) + Val(TextBox3.Value)
This Double can be assigned directly to a worksheet cell.
Cells(4, "A").Value = MySum
Be mindful that Cells(4, "A").Value = TextBox1.Value may not have the same effect because in one case a number is assigned, in the other a string.
In order to update Range("A4") when one of the text boxes changes value you should use the TextBox's BeforeUpdate event. The Change event fires whenever you type a character which will give you a lot of flicker because updates are run before the user finishes typing. With the Before or AfterUpdate events the updating of worksheet cell will occur when the text box being changed loses the focus.
Related
How can I use VBA in excel to determine if a particular cell has one or more buttons in it?
I have a spreadsheet with 50 rows. Each row has a series of data entry fields, and then in column S, there are two buttons to do some calculations based on that data. The buttons all run the same macro, and check which row they are in to determine which row to act on.
Periodically, a user will delete one or more rows, once that data is no longer relevant. When this happens, I want to insert the same number of new rows onto the bottom, to ensure I always have 50 data rows. I can copy and paste e.g. S49 to S50, and the buttons will appear in S50, and work as intended, but I can't tell if one row or n rows have been deleted, so I don't know whether to start copying from S49, S48, or Sn.
If I write a for n = 1 to 50 loop to cycle through each row of column S, how can I check to see if there is a button present in cell Sn?
Edit: with #Michael's answer below I realised I needed to loop through the buttons, not the cells. While Michael's solution correctly answers my question as asked, in my particular application it is a little simpler:
Dim lastBtnRow as Integer
Dim b As Button
lastBtnRow = 0
For Each b In ActiveSheet.Buttons
If b.TopLeftCell.Row > lastBtnRow Then lastBtnRow = b.TopLeftCell.Row
Next
Then it's just a matter of copying and pasting S:lastBtnRow to S:lastBtnRow+1 through S:50
Cells don't have a property that identifies objects sitting in them, but objects have properties about where they're located.
You need to instead build a loop through all buttons on the sheet and test where they're located. If you're dealing with Form Buttons (and not ActiveX Buttons), then this is a simple loop that will count the number of buttons located in the cell you currently have selected:
Sub ButtonLoop()
Dim b As Button, i As Long
For Each b In ActiveSheet.Buttons
If b.TopLeftCell.Address = Selection.Address Then i = i + 1
Next
MsgBox i
End Sub
If you want to check the number of buttons in each cell, you can either write an outer loop that loops through each cell, and then use the loop above as the inner loop to check for buttons in the current cell in the outer loop; or more efficiently use a data structure such as a dictionary to increment a counter for each cell address encountered.
I have created small excel form for updating a database. works great, though staff are doing odd things and have to replace the excel weekly with a clean version. So I am thinking of creating userforms that update the excel sheet(DutySelection).
I have many buttons (userform) A4:A31 that will control a single macro which opens 3 different userforms depending on B4:B31 dropdown list selection
Currently My code only works from B4 no matter which button i click.
EG: B4 selection Start, the Start form opens. B6 selection Finish, the Start form opens
Sub Duty()
If Sheets("DutySelection").Range("B4,B31") = "Start" Then
frmStart.Show
ElseIf Sheets("DutySelection").Range("B4,B31") = "Duty Type" Then
ReportUpdate.Show
Else: Sheets("DutySelection").Range("B4,B31") = "Finish" 'Then
frmFinish.Show
End If
End Sub
I am thinking that i am missing a line or two but just can not find what i am needing online
Sheet.Range("B4,B31") doesn't return what you think it does: it returns a composite range consisting of 2 areas, area 1 being cell B4 and area 2 being cell B31. I.e., the same as you would get when you select cell B4, then Ctrl-Clicked cell B31.
I think you meant "B4:B31", but this also returns something else: an array filled with (the values of) all cells in the range B4 to B31. You cannot compare it with a text string just like that.
What you do want here is to loop through all cells between B4 and B31, then compare their values to the texts you're interested in.
Another issue is that your code only ever acts upon the first text it matches. So, if cell B4 contains "Start", then there's no way the ElseIf will ever be evaluated, not even if cell B5 contains "Duty Type". The best way to deal with this depends on how you get those texts in column B on your sheet.
If I understood you correctly, you have a button in each row next to column B and clicking it invokes the action selected in column B in the corresponsing row, right?
In that case I would suggest that you place 3 buttons next to each other that invoke 3 different macros.
Greetings,
vat
I have a textbox called TextBox 1 which contains paragraphs. I defined it with a name (Insert > Name > Define...) called profile_reference.
On a cell, I inputted the formula =profile_reference but I'm getting the value TextBox 1. What I wanted to do is to get the actual value of that textbox. Is that possible?
I'm using a PHP parser to get values from this excel file and it can not get the value for textboxes, it can only get cell values. So I'm trying to copy the value of that textbox to a cell then parse it.
You can retrieve the contents of the textbox but this will require more than just the standard Excel user interface.
A textbox is a Shape object, and a member of the Worksheet's Shapes collection. When you insert a textbox into a worksheet, Excel gives it a name such as "TextBox 1". Therefore, you can refer to the Shape object containing a textbox in VBA as (for example)
Worksheets("Sheet1").Shapes("TextBox 1")
Because the Shape object can contain a variety of different things (such as pictures or AutoShapes) a few more objects, properties and methods are involved in retrieving the text. The full phrase required is
Worksheets("Sheet1").Shapes("TextBox 1").TextFrame.Characters.Text
which delivers the contents of the textbox as a String.
However, this requires you to use the name of the textbox specified by Excel (i.e. "TextBox 1"). You have added a a name called "profile_reference" which refers to TextBox 1, so how do you get the contents of the textbox using your name rather than the one created by Excel?
A name is a Name object which is part of the Workbook's Names collection. So you can refer to your specific Name object as (for example)
ActiveWorkbook.Names("profile_reference")
and the "refers to" part of the object (the bit you specify using the user interface) is
ActiveWorkbook.Names("profile_reference").Value
The Value property of a Name object is a character string in the syntax of Excel's formulae so in your case this string is
'="TextBox 1"'
i.e. the bit inside the single quotes. This is almost but not quite the 'TextBox 1' string that you want. Therefore, getting at the contents of the textbox using your name requires a little bit of VBA, such as:
Dim strTB As String
strTB = ActiveWorkbook.Names("profile_reference").Value
strTB = Mid(strTB, 3, Len(strTB) - 3) 'Strips unwanted =" and " chars from start/end
MsgBox Worksheets("Sheet1").Shapes(strTB).TextFrame.Characters.Text
I've used a message box to show the contents of the textbox. The contents could equally be assigned to a worksheet cell. You could, if you wanted, wrap this up in a short user-defined function (which perhaps takes your name as its input argument) providing you with a convenient mechanism for placing the contents of the textbox into a worksheet cell.
I have a piece of code that formats cell according to requirements:
Range.Font.Italic = Microsoft.Office.Core.MsoTriState.msoTrue;
Range.HorizontalAlignment = XlHAlign.xlHAlignGeneral;
Range.NumberFormat = "0.0_%_);(0.0)_%;-_%_)";
And this code is invoked then button on custom ribbon is pressed. It's similar to percentage cell format. One more thing I have to add is multiplying the cell value by 100.
For instance
cell value is set to 0.15, I click button and value changes to 15%.
cell value is set to 2.5, I click button and value changes to 250% etc. (very similar to default Excel Precentage cell style)
However, if I do something like this:
decimal result = Convert.ToDecimal(cell.Value);
cell.Value = result * 100;
and user hits button multiple times, value is multiplied every time. Is there a way to specify something like display format, so that actual value is preserved and only displayed value is multiplied by 100? Or another way to prevent value from being multiplied multiple times?
Well you don't need to multiply it by 100
If the cell has .15 then apply the formatting
Range.NumberFormat = "0.00%"
It will automatically change to 15.00 % and you don't need to multiply it by 100.
FOLLOW UP
An out of the box thinking... Why not hide the % symbol by setting the color of the % to white?
VBA CODE
Sub HidePercentage()
Dim Temp As String
Temp = Format(ActiveCell.Value, "0.00%")
With ActiveCell
.NumberFormat = "#"
.HorizontalAlignment = xlRight
.Formula = CStr(Temp)
.Characters(Start:=Len(Temp), Length:=1).Font.ColorIndex = 2
End With
End Sub
SNAPSHOT
A dirty way would be maintain a hidden sheet, Move original value, or maintain flag for that cell in hidden sheet on button click
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