Click here to Skip to main content
16,018,264 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
I have a code it returns error
Unable to cast object of type 'System.String' to type 'Microsoft.Office.Interop.Excel.Worksheet'.

what did i do wrong? I converted it but still ahve error
VB
FoundCell = xlWorkBook.Worksheets(CType(DataGridView1.Rows(i).Cells(1).Value, Microsoft.Office.Interop.Excel.Worksheet)).Range("B14:B20000").Find(WHAT_TO_FIND)
Posted
Updated 12-Sep-15 19:21pm
v3
Comments
F-ES Sitecore 11-Sep-15 4:32am    
It can't convert what is at

DataGridView1.Rows(i).Cells(1).Value

to a Worksheet. Given that your cell is holding a string and a Worksheet is a binary COM object, it's not surprising this cast is failing. What is DataGridView1.Rows(i).Cells(1).Value? Is it a filename? If it's a filename you'll need to use the interop objects API to load the worksheet at that location.

1 solution

This piece of code causes error:
C#
CType(DataGridView1.Rows(i).Cells(1).Value, Microsoft.Office.Interop.Excel.Worksheet)


I'd suggest to get dataGridView cell value into string variable:
C#
string sheetname = DataGridView1.Rows(i).Cells(1).Value;


then to create object variable (of Worksheet):
C#
Microsoft.Office.Interop.Excel.Worksheet wsh = xlWorkBook.Worksheets(sheetname);


Now, you can use Find method[^]: How to: Programmatically Search for Text in Worksheet Ranges[^]

Note that Find method returns Range object!
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900