【发布时间】:2018-01-16 11:30:43
【问题描述】:
我开发了一个 Excel 加载项,可以用数据填充工作表。
填充数据的主循环是:
Excel.Worksheet sheet = workbook.Sheets.Add(After: workbook.Sheets[workbook.Sheets.Count]);
int newRow = 2;
// Llena la hoja con el maestro
foreach (var producto in maestro)
{
sheet.Cells[newRow, 1].Formula = producto.SKU.ToFormula();
sheet.Cells[newRow, 2].Value = producto.Descripcion;
sheet.Cells[newRow, 3].Value = producto.Linea;
sheet.Cells[newRow, 4].Value = producto.Familia;
sheet.Cells[newRow, 5].Value = producto.UltimoCorrelativo;
sheet.Cells[newRow, 6].Value = producto.FechaCreacion;
sheet.Cells[newRow, 7].Value = producto.FechaModificacion;
newRow++;
}
然而,一切都完美无缺,因为这个过程是在 STA 线程中运行的,为了不冻结 UI,用户可以在处理时执行其他操作。其中一项操作是单击单元格。在任何指令中,该操作都会导致应用程序在 for 循环内崩溃。
异常是 HRESULT: 0x800AC472
怎样才能避免呢?
【问题讨论】:
-
也许你可以尝试在处理期间设置一个等待光标,见stackoverflow.com/a/39544078/3205529
-
这不是一个选项,因为这并不能避免用户点击任何地方。另一个选项是使用 VSTO 指令避免用户输入,但不允许单击取消按钮。最后,我使用 try catch 块,如果用户单击单元格并引发异常,则会出现一个消息框,允许用户重试处理。
-
好吧,另一个想法:也许 application.screenupdating 设置为 False,然后设置为 True。但我不确定它是否会阻止选择。