您最初将您的问题标记为vba,但VBA 不会抛出System.InvalidCastException,或任何其他与此相关的异常; vb.net 会。
如果True 是数字,则IsNumeric(True) 返回True。您想验证从数组中检索到的字符串是否为数字;给它从数组中检索到的字符串作为参数:
If IsNumeric(Mid(arr(i), 4, 1)) Then
MsgBox("Number")
End If
您的代码读起来像 VB6/VBA,因为:
Imports Microsoft.VisualBasic
该命名空间包含您根本不需要使用的类似 VB6 的东西。 .net 的美妙之处在于一切都是对象,因此假设数组是String 的数组,您可以调用实际的String 实例方法,而不是VB6 的Mid 函数。
Dim theFifthCharacter As String = arr(i).Substring(4, 1)
或者,因为您只对 1 个字符感兴趣,而 String 本身就是 IEnumerable(Of Char),您可以这样做:
Dim theFifthCharacter As Char = arr(i)(4)
请注意 .net 中的一对一索引从 0 开始,因此如果您想要第 5 个项目,您将获取索引 4。
现在,如果你想看看它是否是数字,你可以try来解析它:
Dim digitValue As Integer
If Int32.TryParse(theFifthCharacter, digitValue) Then
'numeric: digitValue contains the numeric value
Else
'non-numeric: digitValue contains an Integer's default value (0)
End If
最后,如果你想要一个消息框,请使用 WinForms 的 MessageBox 而不是 VB6 的 MsgBox:
Dim digitValue As Integer
If Int32.TryParse(theFifthCharacter, digitValue) Then
'numeric: digitValue contains the numeric value
MessageBox.Show(string.Format("Number: {0}", digitValue))
Else
'non-numeric: digitValue contains an Integer's default value (0)
MessageBox.Show("Not a number")
End If