如何更改 Word.Range 文本而不丢失格式

发布于 2024-07-07 13:18:00 字数 685 浏览 8 评论 0原文

任何人都知道如何更改 Word.Range 对象的文本但仍保留其格式? 例如,如果我有“this text”并将其更改为“that txt”,则 txt 仍将以粗体显示。

我正在寻找一种方法来更改范围的整个文本,而不仅仅是单个单词,因为我从独立的 API 获取新文本,我可以假设新文本和旧文本具有相同的编号的话。

这是我到目前为止得到的:

    for (int i = 0; i < oldWords.Length; i++)
    {
        if (oldWords[i] == newWords[i])
            continue;

        object Replace = WdReplace.wdReplaceOne;
        object FindText = oldWords[i];
        object ReplaceWith = newWords[i];
        var success = Sentence.Find.Execute(parameters stub);
    }            

但由于某种原因,它只在第一次执行中成功,因为范围选择保留在找到的单词上。

编辑:明白了,每次执行后,我都恢复了范围的原始结束位置。

谢谢。

Anyone knows how can I change the text of a Word.Range object but still keeping it's format?
For example if I have "this text" and I change it to "that txt", txt will still be in bold.

I'm looking for a way to change the whole text of the range, not just a single word, as I'm getting the new text from an independent API, I can assume that the new text and the old text have the same number of words.

This is what I got so far:

    for (int i = 0; i < oldWords.Length; i++)
    {
        if (oldWords[i] == newWords[i])
            continue;

        object Replace = WdReplace.wdReplaceOne;
        object FindText = oldWords[i];
        object ReplaceWith = newWords[i];
        var success = Sentence.Find.Execute(parameters stub);
    }            

But for some reason, it only succeeds in the first Execute, because the range selection remains on the found word.

Edit: got it, after each execute, I had restore the original end position of my Range.

Thanks.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

寄与心 2024-07-14 13:18:00

您无法使用 Execute 方法更改文本的格式。
你可以这样做:

Range rng=doc.Content;
rng.Find.Execute(ref finding, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing)

//if this method returns true, you will get the range at the finding location.
if(rng.Find.Found)
{
  rng.Text='sth';
  rng.Bold=0;
}

也许这可以帮助你。

You can't use the Execute method to change the text with formatting.
You can do it like:

Range rng=doc.Content;
rng.Find.Execute(ref finding, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing)

//if this method returns true, you will get the range at the finding location.
if(rng.Find.Found)
{
  rng.Text='sth';
  rng.Bold=0;
}

Maybe this can help you.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文