Delete worksheet from an excel - VB.Net

By default, Microsoft Excel provides three worksheets in a workbook. However, it is possible to programmatically add or delete worksheets as required using a VB.Net application. To delete a worksheet, you need to add a reference to the Microsoft.Office.Interop.Excel assembly, which provides the necessary classes and methods for interacting with Excel files.

Excel Library

To access the Excel object model from Visual VB.Net, you need to add the Microsoft Excel 12.0 Object Library to your project. This library provides the necessary classes, properties, and methods to interact with Excel.

How to add Excel Library

Delete worksheet from an excel file

How to delete worksheet from an excel file from VB.Net

In order to delete worksheet from excel file, this VB.Net program open an existing Excel file and select the worksheet and then delete it.

Dim worksheets As Excel.Sheets = xlWorkBook.Worksheets worksheets(1).Delete()

Delete Excel.Worksheet without prompts

To suppress prompts and alert messages while running a macro in Microsoft Excel, you can set the DisplayAlerts property to False. By doing so, Excel will automatically handle any messages that require a response from the user by choosing the default response.

The following VB.Net source code shows how to programmatically delete Worksheets from Workbooks.

Full Source VB.NET
Imports Excel = Microsoft.Office.Interop.Excel Public Class Form1 Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click Dim xlApp As Excel.Application = New Microsoft.Office.Interop.Excel.Application() If xlApp Is Nothing Then MessageBox.Show("Excel is not properly installed!!") Return End If xlApp.DisplayAlerts = False Dim filePath As String = "d:\test.xlsx" Dim xlWorkBook As Excel.Workbook = xlApp.Workbooks.Open(filePath, 0, False, 5, "", "", _ False, Microsoft.Office.Interop.Excel.XlPlatform.xlWindows, "", True, False, 0, _ True, False, False) Dim worksheets As Excel.Sheets = xlWorkBook.Worksheets worksheets(1).Delete() xlWorkBook.Save() xlWorkBook.Close() releaseObject(worksheets) releaseObject(xlWorkBook) releaseObject(xlApp) MessageBox.Show("Worksheet Deleted!") End Sub Private Sub releaseObject(ByVal obj As Object) Try System.Runtime.InteropServices.Marshal.ReleaseComObject(obj) obj = Nothing Catch ex As Exception obj = Nothing Finally GC.Collect() End Try End Sub End Class