Invoke code - Exception has been thrown by the target of an invocation

Hi,

I am trying to delete sheet1 from excel using below code but i am getting error, can someone help ?

Dim xlApp As Microsoft.Office.Interop.Excel.Application
Dim wb As Microsoft.Office.Interop.Excel.Workbook

xlApp = New Microsoft.Office.Interop.Excel.Application
wb = xlApp.Workbooks.Open(in_FilePath)

xlApp.DisplayAlerts = False
TryCast(wb.Sheets(in_SheetName), Microsoft.Office.Interop.Excel.Worksheet).Delete()
xlApp.DisplayAlerts = True

wb.Save()
wb.Close()

Hi @Sirisha_Siri,

There are multiple ways to delete a sheet:

  1. Using Delete Sheet activity from Excel Package or from component BalaReva Excel Activities - RPA Component | UiPath Marketplace
  2. Delete all the data in the ExcelSheet using the Excel.Delete.Range activity - #6 by balupad14
  3. How To Delete Sheets From An Excel File Programmatically – In UiPath – ExcelCult

Hope this helps.
Thanks,
Ashwini Kempraj

1 Like

Hi @Sirisha_Siri

Please check in debug mode whether any variable or argument is holding null value.

Also try to kill any excel objects open before invoke code using kill process activity.

@Sirisha_Siri

Make sure you pass the file path (in_FilePath) and Sheet name (in_SheetName) through the mentioned arguments. Try below steps click on Edit Arguments

Capture1

Pass the excel file path and sheet name

Hi @Sirisha_Siri ,

To understand more about the error being faced inside the Invoke Code, try using Try Catch Block inside it like the below Updated Code.

We would require to handle the Exceptions inside Invoke Code Activity to be able to understand where/what was the exact error.

Try
	Dim xlApp As Microsoft.Office.Interop.Excel.Application
	Dim wb As Microsoft.Office.Interop.Excel.Workbook
	
	xlApp = New Microsoft.Office.Interop.Excel.Application
	wb = xlApp.Workbooks.Open(in_FilePath)
	
	xlApp.DisplayAlerts = False
	TryCast(wb.Sheets(in_SheetName), Microsoft.Office.Interop.Excel.Worksheet).Delete()
	xlApp.DisplayAlerts = True
	
	wb.Save()
	wb.Close()
Catch e As Exception
	Console.WriteLine(e.Message+" at "+e.Source)
End Try

Let us know if the above gives out a precise error that we can point to and work on fixing this error.
You should Check the Output Panel for the Error message that is being logged.

Also, Do note that, if the Excel has only one sheet present, the Delete operation will give out an Error, as there should be atleast one Sheet present in the Excel.