Get the value of a textbox to a cell - excel

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.

Related

Hyperlink.Address property returns partial URL after hash character

If a cell hyperlink points to a URL that contains #, the Address property of the Hyperlink object only returns everything up to that character.
For instance, create a cell with any content and add a hyperlink to, e.g. http://www.google.com/#Test. Then, run the following macro after selecting that cell:
Sub ShowURL()
MsgBox (Selection.Hyperlinks(1).Address)
End Sub
Here is all you get:
Does Excel process characters after # differently (e.g. if they are assumed to be anchors)?
I finally got it: everything after # is returned by the SubAddress property.

Changing text in shape textbox but getting "index into the specified collection is out of bounds" error

I am trying to change the text in named shape text boxes that are copied from another sheet and retain the same name, but I keep getting the error
-2147024809 index into the specified collection is out of bounds
I've tried changing the names, using standard text boxes, and changing the text on the original sheet but nothing is working
Worksheets("Sheet2").Range("A21:D37").Copy
Worksheets("Sheet1").Paste Destination:=Worksheets("Sheet1").Range("A9")
'This is the code that copies what i need from the other sheet that brings the shape text boxes with it
Worksheets("Sheet1").Shapes(shapeTextBox1).TextFrame.Characters.Text = stringVariable
'it throws the error on this line of code
it should show up as the string value i have set up for stringVariable but it is giving me the error code
Instead of trying to change the text in the shape text box directly, i linked each textbox to a cell and had the vba code change that
NOTE: I did have to lock the link to the cell or it would try to take that same cell address of the page i was pasting it to (='Sheet1'!$A$1)

Excel - Replace cell link in formula with value in cell

I'm trying to figure clean up a spreadsheet - but I'm trying to avoid typing out a lot of hardcoded values that are referenced in formulas.
So right now, I have a function that takes a string
=FunctionThatWantsAString(A1,SomeOtherInputs)
In Cell A1 I have "SomeString"
Is there a way to easily replace the cell link "A1" in the formula with the string "SomeString"?
Thanks
The simple solution is to go to the Formulas ribbon > Defined Names > Name Manager > New [or simply select A1, and then click on the NameBox which says "A1" and type in "SomeString"]
This allows you to name a specified range. You can then refer to that name either within an excel worksheet or within VBA.
Edit for additional request
If you don't want A1 to have to hold the text "SomeString", you can actually use the name manager to create a name which refers to a string. ie: you can have the Name SomeString be equal to "asdf". Then, use ctrl+f to find and replace all instances of "A1," in your worksheet with "SomeString".
Alternatively , just use ctrl+f to find and replace "A1" with ""asdf"", and have your results hardcoded directly in all cells. Probably not recommended to do that though, for maintenance purposes.
If you are using a User Defined Function, you should check if that first parameter is a cell value, and if so, get the value.
Public Function test(st As Variant)
If TypeName(st) = "Range" Then
'get the value of the range or use the string passed in
'or if TypeName(st)="String"
End If
test = TypeName(st)
End Function

Excel - Is it possible to declare variables for specific words?

I'm working in a test cases spreadsheet in Excel, last week I ran into a problem, the DEV team decided to change a lot of 'field' labels of the application under test. What I had to do is go to my Excel spreadsheet and modify the labels' name one by one.
What I want to do now is define the names of the labels as variables and then make the changes directly from the variables instead of doing it by occurrence.
For example, I wrote:
"The user inputs the username in 'Name' field".
I want 'Name' to be pulled from a variable so next time they decide to change the label name, e.g: from 'Name' to 'User-Name', I have to only change the variable name from 'Name' to 'User-Name' rather than doing this manually in each occurrence.
Any idea on how can I do this in Excel?
Thanks in advance!
Named Ranges might be beneficial to you. You can refer to a Range of cells by a name and if you ever add columns or rows the Named Range will automatically increment the reference to the Range. Look under the Formulas menu and click on Name Manager. From there you can define a name for any cell range you would like, say:
MyRange = A1:C1
and refer to it in VBA like:
Range("MyRange")
On a WorkSheet you can simply refer to it like this
=MyRange
Sure. Just make a 2-column list in a separate worksheet, where column A is the variable name and column B is the corresponding value. Everywhere you want to reference a specific variable name, perform a VLOOKUP() against that 2-column list.
="The user inputs the username in '"&VLOOKUP("Name",Sheet1!$A$1:$B$30,2,FALSE)&"' field."
Or you wouldn't even need to do the VLOOKUP if you chose to use a one-column list with no field labels. You could refer directly to the cell you want with concatenation, i.e.:
="The user inputs the username in '"&Sheet1!$A$1&"' field."
Even easier, which wouldn't require any special entries would just be to do a global find/replace, which is made more convenient since your fields are enclosed by single quotes. I.e., there's nothing stopping you from replacing all occurrences of 'Name' with 'User-name'.
For example, I wrote: "The user inputs the username in 'Name' field".
If this is in an Excel sheet, you can just concatenate a cell reference into your text. For example, if the field header "User-Name" is in A1 on Sheet1, you would use a formula like this:
="The user inputs the username in '" & Sheet1!$A$1 & "' field."
If you're trying to do this in VBA code, you can always declare constant string variables.
Const strName as String = "Name"
then use it in the code, for example:
MsgBox "The user inputs the username in " & strName & " field"
Hope that helps :)

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