2

これは、アプリケーション レベルのアドイン内で試行されます。Range を展開するためのドキュメントは、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);

なぜこれが事実なのですか?

4

1 に答える 1

1

ご存知のように、相互運用性のバグだと思います。私がそれを回避した方法は、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;
        }
于 2020-05-07T15:34:35.087 に答える