I have:
Public Class ExcelProcess
Private App As New Excel.Application
Private Books As Excel.Workbooks = App.Workbooks
Private WB As Excel.Workbook
Public Sub deleteSheets()
Dim sheet As Excel.Worksheet = getSheetToDelete()
sheet.Activate()
sheet.Delete()
WB.Save()
WB.Close()
End Sub
Private Function getSheetToDelete() As Excel.Worksheet
Try
WB = Books.Open("file.xlsx")
Catch ex As Exception
InputOutput.print(ex.Message)
End
End Try
Return WB.Sheets(1)
End Function
End Class
I ran the above code, and it ran successfully with absolutely no errors or exceptions!
But the sheet didn’t get deleted!
< UPDATE >
I have also tried:
sheet.Select()
sheet.Delete()
' Now, this gave me an exception:
Unhandled Exception: System.Runtime.InteropServices.COMException: Exception from HRESULT: 0x800A03EC
at Microsoft.Office.Interop.Excel._Worksheet.Select(Object Replace)
at DealerCapReport.ExcelProcess.deleteSheets()
at DealerCapReport.MainModule.Main()
< Another UPDATE >
I tried to check sheet.Delete() boolean for success of failure:
If sheet.Delete() Then ' Error: Expression does not produce a value.
Console.WriteLine("Can-not Delete")
End If
It says Error: Expression does not produce a value. in sheet.Delete().
The strange thing is that the Microsoft API reference says that it would produce a Boolean, but it doesn’t as it is a Sub and not a function.
How and what is happening?
Am I doing something wrong?
Please help me fix this!
The following code works for me (EDITED to include some error checking):