将域代码添加到INCLUDEIMAGE字段

时间:2019-02-24 22:57:55

标签: c# ms-word office-interop word-field

当通过Interop将字段添加到现有Word文档中时,我们需要设置“未与文档一起存储的数据”标记(“ \ d”),但无法确定如何做到这一点。

此示例在插入图像链接方面效果很好,但它将图像存储在文档中,而不是远程存储(我们需要)。

currentlySelectedSheet.Select

任何人将不胜感激。 谢谢。

1 个答案:

答案 0 :(得分:0)

有多种方法可以将开关添加到域代码中。

在问题中出现的情况下,可以将开关添加到传递到Text参数的字符串中:

    if (doc.Bookmarks.Exists("TrackingPixel"))
    {
        string fieldSwitches = " \d";
        object oBookMark = "TrackingPixel";
        object newText = @"https://www.remotelocation.com/trackingpixel/secretcode" + fieldSwitches;

        Range rng = doc.Bookmarks.get_Item(ref oBookMark).Range;
        // There's usually no need to select the Range unless the user should work with it
        //rng.Select();

        rng.Fields.Add(
            Range: rng,
            Type: WdFieldType.wdFieldIncludePicture,
            Text: newText,
            PreserveFormatting: true
            );
    }

如果这是现有的域代码(应在事实之后添加开关),则可以为字符串分配新内容。例如:

string fldCode = field.Code.Text;
fldCode += " \d";
field.Code.Text = fldCode;
field.Update();

FWIW在添加字段时,我经常将整个字段代码作为字符串传递(仅使用Text参数),而忽略了Type参数。除非我知道我明确想要这种行为,否则我还将PreserveFormatting设置为false。首先是个人喜好。第二,当域代码更新为其他(格式化的字符串)内容时,\* MergeFormat开关会导致非常奇怪的行为。但是,我将它用于链接表。