Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to add text to an existing shape(textbox) in C# Excel Interop

I have an excel which contains textboxes/shapes which I am going to fill in with specific data. I used the following code in identifying each shape:

//using Excel = Microsoft.Office.Interop.Excel;

Excel.Worksheet xlWorkSheet
foreach(Excel.Shape shp in xlworksheet.Shapes)
{
    //code to add text to shape goes here....
}

I also tried using:

shp.TextFrame2.TextRange.Characters.Text = "Test";

and

shp.TextFrame.Characters(Type.Missing, Type.Missing).Text = "Test";

but gives an error which states The specified value is out of range and Member not found. (Exception from HRESULT: 0x80020003 (DISP_E_MEMBERNOTFOUND)), respectively.

What should be the correct approach in adding texts to existing textboxes?

like image 777
ThEpRoGrAmMiNgNoOb Avatar asked Mar 15 '23 10:03

ThEpRoGrAmMiNgNoOb


1 Answers

You have to check if the type of Shape is msoTextBox before setting text.

Excel.Worksheet xlWorkSheet
foreach (Excel.Shape shp in xlworksheet.Shapes)
{
    if (shp.Type == Microsoft.Office.Core.MsoShapeType.msoTextBox)
    {
        shp.TextFrame.Characters(Type.Missing, Type.Missing).Text = "Test";
    }
}
like image 117
jhmt Avatar answered Apr 06 '23 08:04

jhmt