类型不匹配错误,为什么?

时间:2014-03-19 12:26:10

标签: excel vba excel-vba type-mismatch

如果范围... 运行时,有人可以解释为什么类型不匹配吗? 这是我的代码

Sub Button2_Click()
Dim i As Integer
Dim k As Integer
For i = 2 To 1000
For x = 3 To 999
If Range("k" & i & ":bn" & i).Value = Range("k" & x & ":bn" & x).Value And Cells(i, 5).Value <> Cells(x, 5).Value Then
Range("k" & i & ":bn" & i).Interior.ColorIndex = 7
Range("k" & x & ":bn" & x).Interior.ColorIndex = 7
End If
Next x
Next i

End Sub

我尝试使用Cstr(),但没有改变

UP:我已经尝试再使用一个循环和单元格而不是范围,我得到的只是应用程序定义或对象定义的错误:

Dim z As Integer
...
For z = 6 To 30
If Cells(i, z).Value = Cells(x, z).Value And Cells(i, 5).Value <> Cells(x, 5).Value Then

提前预订

1 个答案:

答案 0 :(得分:2)

问题在于你试图比较相同的两个范围&#34;形状&#34;但不止一个细胞。 Excel VBA不允许这样的内容:

Sub test1()
    Dim r1 As Range, r2 As Range
    Set r1 = Range("A1:A2")
    Set r2 = Range("B1:B2")
    If r1.Value = r2.Value Then
        MsgBox "same"
    End If
End Sub

将失败.............你需要逐个元素比较,如:

Sub test2()
    Dim r1 As Range, r2 As Range
    Set r1 = Range("A1:A2")
    Set r2 = Range("B1:B2")
    Dim i As Long, b As Boolean
    b = True
    For i = 1 To 2
        If r2(i).Value <> r1(i).Value Then
            b = False
        End If
    Next i
    If b Then
        MsgBox "same"
    End If
End Sub