vba 如何删除 Word.Selection?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/6737019/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-11 13:40:21  来源:igfitidea点击:

How to remove a Word.Selection?

vbaoutlookms-wordvstoadd-in

提问by Baadal Gupta

In the context of an Outlook add-on using the WordEditor from the Outlook.Inspector I would like to remove the selection after replacing it with a custom text.

在使用 Outlook.Inspector 中的 WordEditor 的 Outlook 加载项的上下文中,我想在将其替换为自定义文本后删除该选择。

For example, if I select something I can change the selection to a custom text as follows:

例如,如果我选择某些内容,我可以将选择更改为自定义文本,如下所示:

Word.Selection sel = doc.Windows[1].Selection;
Word.Range range = sel.Range;

    if(sel.Text.Length == 0) {
        MessageBox.Show("No Text is selected");

        return;
    }

sel.Text = "New Text";
sel.Collapse();

If I call this function again, now sel.Text.Length is equal to 1 instead of 0.

如果我再次调用这个函数,现在 sel.Text.Length 等于 1 而不是 0。

回答by Hüseyin DEM?RTA?

I had the same problem in MS Word. Word has a method called Selection.Move(). If you use it it will deselect the selected text and place the cursor at the end of the selected text. For example you can use

我在 MS Word 中遇到了同样的问题。Word 有一个名为 Selection.Move() 的方法。如果您使用它,它将取消选择所选文本并将光标置于所选文本的末尾。例如,您可以使用

ThisAddIn.Application.Selection.Move()

This works in a Word add in if you want to deselect selected text, it may work in Outlook too, try and let me know

如果您想取消选择选定的文本,这适用于 Word 插件,它也可以在 Outlook 中使用,请尝试让我知道

回答by collapsar

You might wish to try

你可能想试试

Selection.Collapse Direction := wdCollapseStart

This will set the start and end positions of the current selection to the same value, namely the start of the current selection (specify wdCollapseEndinstead for the end of the current selection). The result should be programmatically indistinguishable from actually deleting a selection.

这会将当前选择的开始和结束位置设置为相同的值,即当前选择的开始(wdCollapseEnd改为指定当前选择的结束)。结果应该在编程上与实际删除选择没有区别。

hope this helps, carsten

希望这会有所帮助,卡斯滕

applies to: word 2007 (tested), word 2010; possibly other releases

适用于:word 2007(已测试)、word 2010;可能有其他版本