VBA运行时错误类型不匹配

时间:2015-10-05 18:38:25

标签: vba types runtime mismatch

我从编译器

获得以下消息
  

"运行时错误' 13':类型不匹配"

并突出显示以下一行:

If Cells(k, j + 1) = "T1" ... 

我不明白为什么会收到此错误。它循环的单元格都是文本格式。有人可以解释如何更正此代码?请注意,这只是程序的一部分。

Sub TestSub2()

Dim i As Integer, j As Integer, k As Integer, k2 As Integer


'i ->tier table row counter
'j ->column counter
'k ->"Reading Date" and "PM Executed?" table row counter

'---TIER 1 TABLE---
k = 102
k2 = 84


For i = 21 To 35

    k = k + 1
    k2 = k2 + 1

    For j = 26 To 148
        If Cells(k, j + 1) = "T1" Or "T1, T2" Or "T2, T1" Or "T1, T3" Or "T3, T1" Or "T1, T2, T3" Or "T1, T3, T2" Or "T2, T1, T3" Or "T2, T3, T1" Or "T3, T1, T2" Or "T3, T2, T1" Then
    'then
        Cells(i, 8) = Cells(i, j) And Cells(i, 9) = Cells(k2, j + 1)
    End If

    Next j

Next i

2 个答案:

答案 0 :(得分:1)

Logical Operators中的{p> OrAnd,因此用于比较两个或多个表达式并返回Boolean值。

如果要在同一行上执行两个语句,可以使用冒号:来执行此操作:

Cells(i, 8).Value = Cells(i, j).Value: Cells(i, 9).Value = Cells(k2, j + 1).Value

然而,这通常会降低代码的可读性,因此未在中广泛使用。

还有其他方法可以使用布尔比较,例如Select Case或使用较少的Like运算符进行有限的模式匹配。例如:

If Cells(k, j + 1).Value Like "T[1-3]((, T[1-3])+)?" Then
    '// Do something
Else
    '// Do something Else
End If

或许是Select Case块:

Select Case Cells(k, j + 1).Value
    Case "T1", "T1, T2", "T2, T1", "T1, T3", "T3, T1" '// etc...
        '// Do Something
        '// You could include further tests such as...
    Case "Test 1", "Test Another"
        '// Also do something...
        '// Or code for the chance that none of the conditions are met:
    Case Else
        '// Nothing matched - do something else.
End Select

然而,您的原始代码需要看起来更像这样:

If Cells(k, j + 1).Value = "T1" Or Cells(k, j + 1).Value = "T1, T2" Or _
    Cells(k, j + 1).Value = "T2, T1" Or Cells(k, j + 1).Value = "T1, T3" Or _
    Cells(k, j + 1).Value = "T3, T1" Or Cells(k, j + 1).Value = "T1, T2, T3" Or _
    Cells(k, j + 1).Value = "T1, T3, T2" Or Cells(k, j + 1).Value = "T2, T1, T3" Or _
    Cells(k, j + 1).Value = "T2, T3, T1" Or Cells(k, j + 1).Value = "T3, T1, T2" Or _
    Cells(k, j + 1).Value = "T3, T2, T1" Then

        Cells(i, 8).Value = Cells(i, j).Value
        Cells(i, 9).Value = Cells(k2, j + 1).Value

End If

正如您所看到的那样变得相当费力,因此我建议您使用其他方法进行比较。

答案 1 :(得分:0)

“Or”运算符需要分隔布尔表达式,而不是相等右侧的值。改变它:

val = Cells(k, j + 1)
If   val = "T1" Or val = "T1, T2" Or val = "T2, T1" Or val = "T1, T3" Or val = "T3, T1" Or val = "T1, T2, T3" Or val = "T1, T3, T2" Or val = "T2, T1, T3" Or val = "T2, T3, T1" Or val = "T3, T1, T2" Or val = "T3, T2, T1" Then