我正在尝试用列表中的新文本替换word文档中的临时文本。如果文本不是形状,它可以工作,但是一旦它试图在文本框中找到文本就会抛出错误。以下是我到目前为止的情况:
public void FindReplace(List<repvals> replaceVals, string docLocation, int listLen)
{
//Opens a new Word application
var app = new Microsoft.Office.Interop.Word.Application();
//Opens the .docx
var doc = app.Documents.Open(docLocation, true, false);
//Selects the document
var range = doc.Range();
for (int i = 0; i < listLen; i++)
{
//Finds the parameter, then replaces
range.Find.Execute(FindText: Convert.ToString(replaceVals[i].tempVal), Replace: WdReplace.wdReplaceAll, ReplaceWith: Convert.ToString(replaceVals[i].Boxes));
var shapes = doc.Shapes;
//Finds text within textboxes, then changes them
foreach (Microsoft.Office.Interop.Word.Shape shape in shapes)
{
var initialText = shape.TextFrame.TextRange.Text;
var resultingText = initialText.Replace(Convert.ToString(replaceVals[i].tempVal), Convert.ToString(replaceVals[i].Boxes));
shape.TextFrame.TextRange.Text = resultingText;
}
}
//prints document
doc.Save();
doc.Close();
//fully closes Word
Marshal.ReleaseComObject(app);
}
碰到
时会出现问题var initialText = shape.TextFrame.TextRange.Text;
并抛出错误说:&#34;此对象不支持附加文本。&#34;
形状中的文字没有什么特别之处。 (例如tDATE,tNAME等)
有什么想法吗?
答案 0 :(得分:1)
我找到了答案。原来我的代码很好,但是我正在使用的文档(我没写过),在倒数第二页上有另一个形状,以形成一个签名的地方。我用下划线替换它,运行代码,一切都完美地改变了。
对于那些也遇到此问题的人,请尝试检查foreach循环计算的形状数量: http://i.imgur.com/1yNrL4p.png
感谢Andrew和varocarbas的帮助
答案 1 :(得分:0)
*“在2003年,标准文本框的AltText默认值是包含的文本但由于您可以将Alt文本更改为不匹配,因此以这种方式阅读它绝对不是一个好主意。2010年,Alt Text的默认值为空
如果文本框被命名为“文本框2”(如果没有,则替换正确的名称) MsgBox ActiveDocument.Shapes(“文本框2”)。TextFrame.TextRange应该可以工作。“*
- 约翰SR威尔逊