c# - 如何解决 VSTO Word Addin 项目中的错误“值超出范围”
问题描述
我正在 Visual Studio 2019 中创建一个 Word 插件。组合框中有一些文章,当用户选择其中一个时,所选文章的整个文本应粘贴到光标/指针所在的文档中。当文本很短时,这很好用。但是当文本很大时,会发生错误“值超出范围”。
以下是我的功能:(我已经提到了发生错误的行)
private void InsertText(string textToInsert, MyTextStyle myStyle)
{
Word.Selection currentSelection = Globals.ThisAddIn.Application.Selection;
object oldStartPosition = currentSelection.Range.Start;
object oldEndPosition = currentSelection.Range.End;
if (!string.IsNullOrEmpty(myStyle.FontName))
{
currentSelection.Font.Name = myStyle.FontName;
currentSelection.Font.SizeBi = myStyle.FontSize;
}
// Store the user's current Overtype selection
bool userOvertype = Globals.ThisAddIn.Application.Options.Overtype;
// Make sure Overtype is turned off.
if (Globals.ThisAddIn.Application.Options.Overtype)
{
Globals.ThisAddIn.Application.Options.Overtype = false;
}
// Test to see if selection is an insertion point.
if (currentSelection.Type == Word.WdSelectionType.wdSelectionIP)
{
currentSelection.TypeText(textToInsert);
if (string.IsNullOrEmpty(myStyle.FontName))
{
currentSelection.TypeParagraph();
}
}
else
if (currentSelection.Type == Word.WdSelectionType.wdSelectionNormal)
{
// Move to start of selection.
if (Globals.ThisAddIn.Application.Options.ReplaceSelection)
{
object direction = Word.WdCollapseDirection.wdCollapseStart;
currentSelection.Collapse(ref direction);
}
currentSelection.TypeText(textToInsert);
currentSelection.TypeParagraph();
}
else
{
// Do nothing.
}
if (!string.IsNullOrEmpty(myStyle.FontName))
{
object newEndPosition = (int)oldEndPosition + textToInsert.Length - 1;
//The Error occurs on below line:
Word.Range range = Globals.ThisAddIn.Application.ActiveDocument.Range(ref oldEndPosition, ref newEndPosition);
range.Font.Name = myStyle.FontName;
range.Font.SizeBi = myStyle.FontSize;
}
Globals.ThisAddIn.Application.Options.Overtype = userOvertype;
}
解决方案
推荐阅读
- ionic-framework - 搜索栏 (ionInput) 事件过滤输出
- apache-nifi - 如何使用 Jolt 组合两个数组来创建键值对?
- python - 在 Python 中使用 darkskylib 库时出现错误请求错误
- vhdl - VHDL LR移位器循环未更新
- c# - 连接到 ASP.NET Core SignalR API 服务器到 uwp signalR 客户端
- r - 如何在emmeans图中添加颜色?
- laravel-5 - Laravel 通过关系
- android - 在广播接收器中访问 ViewModel 生成的数据
- node.js - 我正在尝试通过 npm 安装 web3 模块
- android - 使用 Xamarin 表单在 Xamarin 中共享图像和声音