在应用程序级外接程序中尝试此操作。扩展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);
为什么会这样?
你知道,我认为这是互操作中的一个错误。我解决这个问题的方法是使用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;
}