邮件合并到多个文本框Word
本文关键字:文本 Word 合并 | 更新日期: 2023-09-27 18:04:27
我有一个模板Word文档,其中包含多个文本框顶部的形状(给它一个更好的边框轮廓比什么可以实现我的文本框的轮廓)。这些文本框包含我希望合并到的邮件合并字段。我有下面的代码在尝试做这个
foreach (Microsoft.Office.Interop.Word.Range range in document.StoryRanges)
{
foreach (Microsoft.Office.Interop.Word.Field field in range.Fields)
{
if (field.Code.Text.Contains("Test Field"))
{
field.Select();
application.Selection.TypeText("test");
}
}
问题是这只改变了第一个文本框内的字段,我已经在这里和MSDN上搜索了一个解决方案,但是我仍然很难找到一个解决方案。我还添加了以下几行,试图找出一些
Console.WriteLine(document.StoryRanges.Count);
在foreach循环中也有
Console.WriteLine(range.Fields.Count);
对WriteLine的第一个调用表明有两个storyrange,一个是主文档,另一个是所有文本框所在的范围。然而,第二个WriteLine表示第一个范围有0个字段,而第二个范围只有1个字段,尽管我使用的模板文档包含超过10个字段。
StoryRanges是嵌套的吗?它们是不同类型的吗?
如果是,你应该考虑使用StoryRange。下面建议的NextStoryRange:http://word.mvps.org/faqs/customization/ReplaceAnywhere.htm
'Iterate through all story types in the current document
For Each rngStory In ActiveDocument.StoryRanges
'Iterate through all linked stories
Do
With rngStory.Find
.Text = "find text"
.Replacement.Text = "I'm found"
.Wrap = wdFindContinue
.Execute Replace:=wdReplaceAll
End With
'Get next linked story (if any)
Set rngStory = rngStory.NextStoryRange
Loop Until rngStory Is Nothing
Next