字词互操作范围:以行为单位扩展被认为是一个坏参数

问题描述 投票:2回答:1

这是在应用级插件中尝试的。扩大范围 表明提供一个 WdUnits 参数作为引用对象应该会成功。而且它确实成功了,对于大多数的 WdUnits 收藏。但是,令人费解的是,不为 WdUnits.wdLine. 以下代码似乎总是失败。

object lineUnit = WdUnits.wdLine;
var rng = document.Range(document.Content.Start, document.Content.Start);
// throws COMException with ErrorCode -2146824168: Bad Parameter
tempRange.Expand(ref lineUnit);

但同样的操作在一个 Selection 成功了。

object lineUnit = WdUnits.wdLine;
document.Range(document.Content.Start, document.Content.Start).Select();
// Word groks this happily
Globals.ThisAddIn.Application.Selection.Expand(ref lineUnit);

到底为什么会这样?

c# visual-studio-2013 ms-word vsto word-2013
1个回答
1
投票

你知道,我认为这是一个interop的bug。我解决这个问题的方法是使用wdSentence,并为表格写其他代码(用来识别行)。 我必须为我的DeleteWhere包装方法做这个。

        public bool DeleteWhere(string value, StringContentType type = StringContentType.Item, bool caseSensitive = true)
        {
            if (string.IsNullOrWhiteSpace(value))
            {
                return false;
            }
            bool ret = false;
            if (type == StringContentType.Line)
            {
                ret = DeleteRowWhere(value, caseSensitive);
            }
            object mytype = type.ToWdUnits();
            if (type == StringContentType.Line)
            {
                mytype = Microsoft.Office.Interop.Word.WdUnits.wdSentence;
            }
            Microsoft.Office.Interop.Word.Range range = doc.Content;
            object matchword = true;
            while (range.Find.Execute(value, caseSensitive, matchword))
            {
                range.Expand(ref mytype);
                range.Delete();
                ret = true;
            }
            return ret;
        }

        private bool DeleteRowWhere(string value, bool caseSensitive = true)
        {
            bool ret = false;
            string search = caseSensitive ? value : value?.ToUpperInvariant();
            foreach (Microsoft.Office.Interop.Word.Table table in doc.Tables)
            {
                for (int x = 1; x <= table.Rows.Count; x++)
                {
                    for (int y = 1; y <= table.Columns.Count; y++)
                    {
                        string val = caseSensitive ? table.Cell(x, y).Range.Text : table.Cell(x, y).Range.Text?.ToUpperInvariant();
                        if (val != null && val.Contains(search))
                        {
                            table.Rows[x].Delete();
                            ret = true;
                        }
                    }
                }
            }
            return ret;
        }
© www.soinside.com 2019 - 2024. All rights reserved.