当从vb.net中删除单元格时,从'Object(,)'types转换为'String'types无效

我试图删除在范围B2到T5000,以字hello开头的所有单元格,但是我不断得到从types'对象(,)'到types'string'的转换不是有效的错误。 任何帮助,将不胜感激。

Dim xlCell As Excel.Range = Nothing xlCell = xlWsheet2.Range("B2:T5000") For Each cell In xlCell If xlCell.Value IsNot Nothing Then If CStr(xlCell.Value).StartsWith("Hello") Then xlCell.Delete() End If End If Next End If End If Next 

看起来像你没有在循环中使用局部variables。 它应该是:

 For Each cell In xlCell If cell.Value IsNot Nothing Then If CStr(cell.Value).StartsWith("Hello") Then cell.Delete() End If End If Next 

命名您的范围xlCell不帮助您debugging。 也许xlRange更合适?

话虽如此,我认为你的列举有点不合适。 像这样的东西应该工作:

 Dim xlRange As Excel.Range = Nothing xlRange = xlWsheet2.Range("B2:T5000") For Each rCell As Excel.Range In xlRange.Cells If rCell.Value IsNot Nothing Then If rCell.Value.ToString.StartsWith("Hello") Then rCell.Delete() End If End If Next