无法将类型为"System.String"的对象转换为类型为"Microsoft.Office.Interop.Excel.Worksheet". [英] Unable to cast object of type 'System.String' to type 'Microsoft.Office.Interop.Excel.Worksheet'.

查看:353
本文介绍了无法将类型为"System.String"的对象转换为类型为"Microsoft.Office.Interop.Excel.Worksheet".的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个返回错误的代码

无法将类型为"System.String"的对象转换为类型为"Microsoft.Office.Interop.Excel.Worksheet".


我做错什么了?我进行了转换,但仍然出现错误

 FoundCell = xlWorkBook.Worksheets( CType (DataGridView1.Rows(i).Cells( 1 ).Value,Microsoft.Office.Interop.Excel.Worksheet)).Range(" ).Find(WHAT_TO_FIND)

CType(DataGridView1.Rows(i).Cells( 1 ).Value,Microsoft.Office.Interop.Excel.Worksheet) pre>

我建议将dataGridView单元格值转换为字符串变量:

  string  sheetname = DataGridView1.Rows(i).Cells( 1 ) .Value; 



然后创建(工作表的)对象变量:

 Microsoft.Office.Interop.Excel.Worksheet wsh = xlWorkBook.Worksheets(sheetname); 



现在,您可以使用查找方法 [ ^ ]:如何:以编程方式在工作表范围内搜索文本 [^ ]

请注意, Find方法将返回Range对象!


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

FoundCell = xlWorkBook.Worksheets(CType(DataGridView1.Rows(i).Cells(1).Value, Microsoft.Office.Interop.Excel.Worksheet)).Range("B14:B20000").Find(WHAT_TO_FIND)

解决方案

This piece of code causes error:

CType(DataGridView1.Rows(i).Cells(1).Value, Microsoft.Office.Interop.Excel.Worksheet)



I''d suggest to get dataGridView cell value into string variable:

string sheetname = DataGridView1.Rows(i).Cells(1).Value;



then to create object variable (of Worksheet):

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!


这篇关于无法将类型为"System.String"的对象转换为类型为"Microsoft.Office.Interop.Excel.Worksheet".的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆