Click here to Skip to main content
15,886,689 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
I'm working on an application which requires me to create an excel worksheet in an existing workbook if the worksheet name doesn't exist and to replace it if it already exists.
I've tried using the code below but I get an error which says "Object reference not set to instance of an object". Please any ideas what is going wrong ?
This is the code.
C#
foreach (Worksheet wsheet in entire_workbook.Worksheets)
if (wsheet.Name.Equals(sheet_name))
{
    Excel.DisplayAlerts = false;
    wsheet.Delete();
    entire_workbook.Save();
    Excel.DisplayAlerts = true;
    break;
}
weekly_worksheet = (Worksheet)weekly_workbook.Sheets[1];
//entire_worksheet = (Worksheet)entire_workbook.Worksheets.Add(Missing.Value, Missing.Value, Missing.Value, Missing.Value);
weekly_worksheet.Copy(entire_worksheet, Missing.Value); //error occurs here
entire_workbook.Save();
weekly_workbook.Save();
entire_workbook.Close(false, Type.Missing, Type.Missing);
Posted
Updated 14-Mar-14 1:09am
v3
Comments
Richard MacCutchan 14-Mar-14 6:50am    
Which line throws the exception?
Emejulu JVT 14-Mar-14 7:11am    
weekly_worksheet.Copy(entire_worksheet, Missing.Value); //error occurs here

1 solution

Looping through the collection of worksheets in inefficient. Rather use something similar to this:
C#
try
{
Worksheet wsh = YourWorkbook.Worksheets["WorksheetName"];
wsh.Delete();
}
catch (...)
{
   //do not inform about errors ;)
}
//now you can add worksheet with the same name ;)


Note: Not tested!
 
Share this answer
 
v2

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900