Calendar

<<  mars 2010  >>
lumamejevesadi
22232425262728
1234567
891011121314
15161718192021
22232425262728
2930311234

View posts in large calendar
Disclaimer
The opinions expressed herein are my own personal opinions and do not represent my employer's view in anyway.

© Copyright 2010

(avril 7, 2008 12:00)

If you dynamically add worksheets, you may need to delete them also. How to do that ? Simple. You can write a simple function as :

/// <summary>

/// Delete all the worksheet from the given collection, except the ones that are named

/// accordingly to one of the given name

/// </summary>

/// <param name="worksheets">The collection of worksheet we want to clean</param>

/// <param name="excludedNames">The names of the worksheet we want to keep</param>

public static void DeleteWorksheets(IExcel.Sheets worksheets, params string[] excludedNames)

{

   for ( int i = worksheets.Count; i > 0; i-- )

   {

      IExcel.Worksheet sheet = worksheets[i] as IExcel.Worksheet;

      if ( !excludedNames.Contains(sheet.Name) )

         sheet.Delete();

   }

}

How to use it ? Well if you are in a sheet code and that you want to delete all the sheets except the current one, you can do :

ExcelUtils.DeleteWorksheets(Globals.ThisWorkbook.Worksheets, this.Name);

Almost good. You will simply notice that each time Excel wants to delete a sheet, you will get a popup asking to confirm the deletion. How to bypass it ? Let's modify our function as follows :

/// <summary>

/// Delete all the worksheet from the given collection, except the ones that are named

/// accordingly to one of the given name

/// </summary>

/// <param name="worksheets">The collection of worksheet we want to clean</param>

/// <param name="excludedNames">The names of the worksheet we want to keep</param>

public static void DeleteWorksheets(IExcel.Sheets worksheets, params string[] excludedNames)

{

   //1. DisplayAlerts = true : will display confirmation popup for the deletion.

   //   to do a silent deletion, we'll set it to false (but save the old values to restore it)

   bool displayAlerts = worksheets.Application.DisplayAlerts;

   try

   {

      worksheets.Application.DisplayAlerts = false;

 

      for ( int i = worksheets.Count; i > 0; i-- )

      {

         IExcel.Worksheet sheet = worksheets[i] as IExcel.Worksheet;

         if ( !excludedNames.Contains(sheet.Name) )

            sheet.Delete();

      }

   }

   finally

   {

      worksheets.Application.DisplayAlerts = displayAlerts;

   }

}

And here we are !

Billets liés

Ajouter un commentaire


 

  Country flag





Live preview

mars 12. 2010 15:37

Powered by BlogEngine.NET 1.2.0.0 | Theme by Pierre-Emmanuel Dautreppe