Question

A user has provided me with an Excel document that has textboxes in a few of the cells. I have the usual setup code to load the Excel application, get the worksheet, and then start iterating the used range. When I try to get the value of the cell that contains the textbox, the value is null.

foreach (Range row in usedRange.Rows) {
    object[,] valueArray = (object[,])row.get_Value(XlRangeValueDataType.xlRangeValueDefault);
    var value = valueArray[1,10];  // This is null for textbox cells
}

Is there a special method I should use to get the value of the textbox that appears in an Excel worksheet?

Edit with fix and explanation

Stewbob's suggestion of iterating the shapes got me in the right direction. But using the following code, I was getting null exceptions:

for (int i=1; i<shapes.Count;i++){
    var item = shapes.Range[i].Item(1);
    string myString = item.TextFrame2.TextRange.Characters.Text.ToString();
}

After looking at the object in Quickwatch, I noticed something odd about the shape. It was of type msoOLEControlObject. It turns out the values on this Excel document are cut and pasted into Excel from a webpage. Excel was not creating textboxes but OLE boxes. The OLE box did have a 'Value' property so I could access the textboxes value as such:

var shapes = ws.Shapes;
    for (int i=1; i<shapes.Count;i++){
        var item = shapes.Range[i].Item(1);
        var myText = item.OLEFormat.Object;
        if (myText.Object != null) {
            if (myText.Object.Value != null) {
                Console.WriteLine(myText.Object.Value.ToString());
            }
        }
    }

So make sure if you are dealing with pasted objects that you check the value property and not the TextRange property.

Was it helpful?

Solution

If you know the name of the Text Box, you can reference it this way:

ActiveSheet.Shapes.Range(Array("TextBox 1")).Select

If you don't know the name, you can use ActiveSheet.Shapes to iterate through all the shapes on the worksheet.

Getting to the actual text in the TextBox is not very straightforward in VBA. The following code iterates through all the Shape objects on the active worksheet:

Dim shp As Shape
Dim myText As String

For Each shp In ActiveSheet.Shapes
    myText = shp.TextFrame2.TextRange.Characters.Text
Next

Though I see that you are working in C#, so the above code will be a little different, but it at least gives you the object model to get to the text inside the TextBox.

OTHER TIPS

Well, the TextBox isn't actually inside any cell (although it may appear to be).

Instead, you have to get it from the Shapes collection in the WorkSheet.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top