2015-10-20 54 views
2

我有一个包含文本框/形状的excel,我将使用特定数据填充它。我用下面的代码中识别每个形状:如何在C#Excel中将文本添加到现有形状(文本框)Interop

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

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

我也尝试使用:

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

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

但给人其中指出分别The specified value is out of rangeMember not found. (Exception from HRESULT: 0x80020003 (DISP_E_MEMBERNOTFOUND)),一个错误。

将文本添加到现有文本框的正确方法是什么?

+0

您的工作表是否只有文本框形状? – jhmt

+0

@jhmt不是所有的文本框。我将如何阅读只有文本框的所有形状?谢谢你的帮助。 – ThEpRoGrAmMiNgNoOb

+0

您可以通过名称来标识文本框。例如,如果名称是“TextBox 1”,“xlworksheet.Shapes.Item(”TextBox 1“)。TextFrame.Characters(Type.Missing,Type.Missing).Text =”Test“;' – jhmt

回答

3

在设置文本之前,您必须检查Shape的类型是否为msoTextBox

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"; 
    } 
} 
+0

这有助于很多。谢谢。^_ ^ – ThEpRoGrAmMiNgNoOb

相关问题