C#:Copy protected worksheet to another excel file

0

I was trying to copy paste one protected worksheet to another excel file but i`m getting error like

"Invalid index. (Exception from HRESULT: 0x8002000B (DISP_E_BADINDEX))"

C# Code:

try
{
    string startPath = System.IO.Path.GetDirectoryName(
        System.Diagnostics.Process.GetCurrentProcess().MainModule.FileName);
    string filePath = System.IO.Path.Combine(startPath, strPath);

    wBook = xCel.Workbooks.Open(filePath);
    wSheet = (Excel.Worksheet)wBook.Worksheets.get_Item(1);
    wSheet.Copy(Type.Missing, Type.Missing);
    wSheet = (Excel.Worksheet)xlApp.Workbooks[0].ActiveSheet;
    //wSheet = (Excel.Worksheet)xlApp.Workbooks[1].Sheets[1];
}
finally
{
    if (wBook != null)
    {
        wBook.Close();
    }
    if (xlApp != null)
    {
        xlApp.Quit();
    }                
}

Could somebody tel what wrong i`m doing here???

OR

Please tell me if there are any better ways to do this??

Thanks.

c#
excel
vba
asked on Stack Overflow Mar 8, 2013 by user2144293 • edited Jul 9, 2018 by Community

1 Answer

2

I would check:

wSheet = (Excel.Worksheet)wBook.Worksheets.get_Item(1);

or

wSheet = (Excel.Worksheet)xlApp.Workbooks[0].ActiveSheet;

Your error seems to suggest either the wBook or the xlApp has no values in it. This is why the index would be invalid (well rather the workbooks or worksheets are empty. I think)

If it is a protected worksheet, wouldn't the fact its protected stop you copying it?

answered on Stack Overflow Mar 8, 2013 by Scott Sellers

User contributions licensed under CC BY-SA 3.0