I am fighting with a strange problem, I hope someone can help me.
Here is the scenario: I am writing an Excel Vsto Add-In, which transfers some data from an Excel Worksheet to a Word document. Some of the values (Excel) need to be put into a TextBox (Word), which is created by my code as well. Each TextBox has to be on a certain page at a certain location (x,y).
using Word = Microsoft.Office.Interop.Word;
Word.Shape shpTxt = wdDoc.Shapes.AddTextbox(Microsoft.Office.Core.MsoTextOrientation.msoTextOrientationHorizontal, x, y, w, h, pageRange);
shpTxt.Name = "ThisIsMyShape";
The anchor used for this TextBox is pageRange, which is determined by following method:
pageRange = Common.Tools.GetStartOfPage(wdDoc, pageNo);
public static Word.Range GetStartOfPage(Word.Document doc, int pageNo)
{
Word.Range rng;
try
{
rng = doc.ActiveWindow.Panes[1].Pages[pageNo].Rectangles[1].Range;
rng.Collapse(1);
return rng;
}
catch (Exception e)
{
return null;
}
}
So far so good, I can see the TextBox in the Word Document.
Now the problem: later in the code, I need to get certain TextBoxes by name, which I am trying to do via following method:
private Word.Shape GetShapeByName(Word.Document wdDoc, string shapeName)
{
Word.Shape result = null;
for (int shpIdx = 1; shpIdx <= wdDoc.Shapes.Count; shpIdx++)
{
result = null;
if (wdDoc.Shapes[shpIdx].Name == shapeName)
{
result = wdDoc.Shapes[shpIdx];
}
}
return result;
}
The problem is: wdDoc.Shapes.Count
always returns 0, although I clearly added a Shape (TextBox) to the document, and I can see it! I also tried to use wdDoc.InlineShapes.Count
instead, but the same result (Zero).
What am I doing wrong? Why does the Shapes collection of my Word Document not contain any Shape (resp. InlineShapes)?
I hope the code snippets above are sufficient to describe the problem well enough. Thanks in advance for your help!
Michael