Excel VBA if语句多条件运行时错误13

Excel VBA If statement multiple conditions runtime error 13

你好,每当我尝试 运行 以下代码时,我都会收到 运行 时间错误 13 类型不匹配,我不知道为什么或如何解决这个问题。

想法是,如果 a = 8 并且单元格 (i,c) 中的第一个数字 = 6 或 4,那么 excel 应该是这样。

Dim a as integer
Dim c as integer

If a = 8 And (CInt(Left(.Cells(i, c), 1)) = 6 Or CInt(Left(.Cells(i, c), 1)) = 4) Then```

如果您正在阅读的单元格内容为空或不以数字开头,CInt 将抛出运行时错误 13。

您可以改用 Val 函数(return 0 用于 non-numeric 字符串),或者您可以检查字符 "6" resp。 "4" 代替。我还建议使用一个中间变量来保存您正在检查的字符,使代码更具可读性。

dim firstChr as string
firstChr = Left(.Cells(i, c))
If a = 8 And (val(firstChr) = 6 Or val(firstChr) = 4) Then
' or
If a = 8 And (firstChr = "6" Or firstChr = "4") Then