当数据以任何形状和形式出现时,您需要检查它的类型并查看它是否可以转换为所需的类型。我假设你正在使用Excel.Interop
。声明你的价值为Object
并对其进行测试,然后尝试将它
转换例如
' Get single cell value
Dim val as Object = DirectCast(range.Cells[row, col], Excel.Range).Value2
' Test for datatypes
If TypeOf val Is Integer Then
Dim i As Integer = CInt(val)
Else If TypeOf val Is Double Then
....
....
' check all datatypes here
End If
如果你想转换,而不检查类型,你绝对可以运行到转换异常的,如果你尝试通过串去如下
' Get string
Dim val as String = DirecCast(range.Cells[row, col], Excel.Range).Value2.ToString()
Dim i as Integer
Dim done as Boolean
If Not done AndAlso Integer.TryParse(val, i) Then
' Do something with "i"
done = true
End if
' check for other types in similar fashion but order so that types with decimals come after integers
在这种情况下,你可能会遇到一个类型为另一种状态。
Thanks T.S.我会尝试这种方法,并会发布结果,因为我花了很多时间寻找答案。 –