这一切都在 Office 2007 的 C# .NET Excel 互操作自动化中。
假设您创建了两个 Excel 应用程序并为每个应用程序打开同一个工作簿:
app = new Excel.ApplicationClass();
app2 = new Excel.ApplicationClass();
string fileLocation = "myBook.xslx";
workbook = app.Workbooks.Open(fileLocation,
Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing,
Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing,
Type.Missing, Type.Missing, Type.Missing, Type.Missing);
workbook2 = app2.Workbooks.Open(fileLocation,
Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing,
Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing,
Type.Missing, Type.Missing, Type.Missing, Type.Missing);
现在,我想将 workbook2 中发生的任何更改复制到工作簿中。我发现我可以连接 SheetChanged 事件来捕获单元格更改:
app.SheetChange += new Microsoft.Office.Interop.Excel.AppEvents_SheetChangeEventHandler(app_SheetChange);
void app_SheetChange(object Sh, Microsoft.Office.Interop.Excel.Range Target)
{
Excel.Worksheet sheetReadOnly = (Excel.Worksheet)Sh;
string changedRange = Target.get_Address(missing, missing,
Excel.XlReferenceStyle.xlA1, missing, missing);
Console.WriteLine("The value of " + sheetReadOnly.Name + ":" +
changedRange + " was changed to = " + Target.Value2);
Excel.Worksheet sheet = workbook.Worksheets[sheetReadOnly.Index] as Excel.Worksheet;
Excel.Range range = sheet.get_Range(changedRange, missing);
range.Value2 = Target.Value2;
}
你如何捕捉计算变化?我可以连接到计算事件,但唯一传递的是工作表,而不是更新的单元格。我尝试强制 app.Calculate() 或 app.CalculateFullRebuild() 但其他应用程序中没有任何更新。公式更改时不会触发更改事件(即滑块控件会导致 SheetCalculate 事件而不是 SheetChange 事件)
有没有办法查看更新了哪些公式?或者是否有更简单的方法以编程方式实时同步两个工作簿?