首页 > 解决方案 > 如何解决 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;
}

标签: c#vsto

解决方案


推荐阅读