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 ):
Public Class ExcelProcess
Private xlApp As Excel.Application
Private xlBook As Excel.Workbook
Private xlSheet As Excel.Worksheet
Public Sub New(ByVal file As String)
xlApp = New Excel.Application
'xlApp.Visible = True 'for debugging
xlApp.DisplayAlerts = False 'prevent user dialogs
xlBook = xlApp.Workbooks.Open(file)
End Sub
Public Sub Quit()
If Not IsNothing(xlBook) Then
xlBook.Save()
xlBook.Close()
End If
If Not IsNothing(xlApp) Then xlApp.Quit()
End Sub
Public Sub deleteSheet(ByVal Index As Integer)
If Index > xlBook.Worksheets.Count Then
Throw New Exception("You cannot delete a worksheet that does not exist")
Exit Sub
End If
If xlBook.Worksheets.Count = 1 Then
Throw New Exception("You cannnot delete the only worksheet in a workbook")
Exit Sub
End If
xlSheet = CType(xlBook.Worksheets(Index), Excel.Worksheet)
xlSheet.Activate()
xlSheet.Delete()
End Sub
End Class
I would suggest that you need to save your workbook after you do the delete (using SaveAs
). Otherwise it will just delete the in-memory worksheet and when your Excel object goes out of scope it will just close the workbook without saving the changes.
Books.SaveAs(...)
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.