Delete excel worksheet using invoke code

Hi

I’m an getting an issue with with Vb code.It says that Microsoft.Office.Interop.Excel.Worksheet is not defined.

image

I have already imported Microsoft.Office.Interop.Excel.

But still getting this issue.

Thanks
Naman

@Naman_Arora

Try with this

' Add reference to Microsoft.Office.Interop.Excel
Imports Microsoft.Office.Interop.Excel

' Create an instance of the Excel application
Dim excelApp As New Excel.Application()

' Open the workbook
Dim workbook As Excel.Workbook = excelApp.Workbooks.Open("C:\path\to\workbook.xlsx")

' Get the worksheet that you want to delete
Dim worksheet As Excel.Worksheet = workbook.Sheets("Sheet1")

' Delete the worksheet
worksheet.Delete()

' Save and close the workbook
workbook.Save()
workbook.Close()

' Release the Excel objects from memory
System.Runtime.InteropServices.Marshal.ReleaseComObject(worksheet)
System.Runtime.InteropServices.Marshal.ReleaseComObject(workbook)
System.Runtime.InteropServices.Marshal.ReleaseComObject(excelApp)
worksheet = Nothing
workbook = Nothing
excelApp = Nothing

@Naman_Arora

At line 9 you have Mircosoft instead of Microsoft…r and c are interchanged

Try this…as at line 7 you are trying to use the cast again which is not allowed in new .net…and Imports is not possible using invoke code @Manju_Reddy_Kanughula

Dim ExcelApp As New Microsoft.Office.Interop.Excel.Application
Dim wb As Microsoft.Office.Interop.Excel.Workbook = ExcelApp.Workbooks.Open("Filename")
Dim ws As Microsoft.Office.Interop.Excel.Worksheet = DirectCast(wb.Sheets("Sheetname"), Microsoft.Office.Interop.Excel.Worksheet)
ExcelApp.DisplayAlerts = False
ExcelApp.Visible = False
ws.Delete()
ExcelApp.DisplayAlerts = True
wb.Save()
wb.Close()
ExcelApp.Quit()

Hope this helps

cheers