Search code examples
c#exceloffice-interopexcel-interop

Is there a reason to toggle MSExcel.Excel.ApplicationClass.DisplayAlerts?


In a project I've taken over, I found this code:

private MSExcel.Excel.ApplicationClass _xlApp;
. . .
_xlApp.DisplayAlerts = false;
_xlApp.DisplayAlerts = true;

Since I don't know why MSExcel.Excel.ApplicationClass.DisplayAlerts would be toggled from false to true with no code in between, I will leave it like it is for now anyway, but why would this toggle be beneficial or necessary?


Solution

  • One case: If you use a macro/VBA to delete sheets from the workbook and don't want the msgbox saying "Are you want to Delete this worksheet?" to pop up, then you

    _xlApp.DisplayAlerts = false;
    ActiveWorkBook.WorkSheets("Sheet2").delete
    _xlApp.DisplayAlerts = true;
    

    and the code will delete Sheet2 without prompting the user to click ok, and more importantly for me, the routine will run to completion while you're getting coffee.