简体   繁体   English

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

[英]Type mismatch error, why?

Can anyone explain why there is type mismatch when If range... runs? 任何人都可以解释为什么在范围...运行时存在类型不匹配?
here is my code 这是我的代码

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

I tried to use Cstr() but nothing changed 我试图使用Cstr()但没有改变

UP: I've tried to use one more loop and cells instead of range and only thing I get is application-defined or object-defined error for this: 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

tnx in advance tnx提前

The problem is that you are trying to compare two ranges of the same "shape" but more than one cell. 问题是你试图比较相同“形状”但不止一个细胞的两个范围。 Excel VBA does not allow this..something like: 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

will fail.............you need an element-by-element comparison like: 将失败.............你需要逐个元素比较,如:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM