Click here to Skip to main content
15,887,027 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Using C# interop for Word, I can create a table with 5 columns and several rows. I want to insert 2 things into column 5 of a particular row: a number representing a percentage, and a text box. The text box's width is equivalent to the percentage. The text box will be colored and will not contain any text.

My problem is that when I create the text box, it is always anchored to the first column of the row, not the column I request. The offsets (.1") also are calculated relative to the first column. I need to have the text box anchored to the last column.

If I manually edit the document, I can move the text box's anchor to the right cell, and everything looks OK.

Here's the code. It is invoked with [cell] equal to the last cell in the row. That value is correct because the text of the percentage shows up in that cell.

private static Word.Cell SetCellPercent(Word.Cell cell, decimal goal, decimal needed, bool? bold)
{
decimal pct;
float pctfloat, wid, hei;
Word.Shape box;
Word.Range rng;

pct = CalculatePercentDone(goal, needed);
SetCell(cell, (pct * 100).ToString("N0"), null, bold); // Store text into cell and apply attributes

pctfloat = Convert.ToSingle(pct);
wid = BOX_WIDTH * PPI * pctfloat; PPI = Points Per Inch = 72
hei = BOX_HEIGHT * PPI;
rng = cell.Range;

box = cell.Range.Document.Shapes.AddTextbox(Microsoft.Office.Core.MsoTextOrientation.msoTextOrientationHorizontal, .1f * PPI, 0.1f * PPI, wid, hei, rng);
return cell;
}

What I have tried:

I tried other values for [rng], like setting it to the range of the first and last paragraphs in the cell. Same result.
Posted
Updated 15-Mar-16 4:49am

1 solution

This addition causes the textbox's anchor to be in the designated cell:

After setting variable [rng], add this line. Seems to work fine, although the precise reason for it is still a mystery to me.

rng.Collapse(Word.WdCollapseDirection.wdCollapseStart);

See https://social.msdn.microsoft.com/Forums/vstudio/en-US/88626c3f-1b22-46d4-8330-450c616b11bc/word-2007-insert-autoshape-in-table-cell?forum=vsto
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900