在For循环中的If语句中键入Mismatch

时间:2015-05-21 20:18:21

标签: excel vba excel-vba

我在试图找出以下代码为什么给我一个Error '13'时遇到了很多麻烦。我做错了吗?

Sub summary()
    Dim last As Variant
    lastrow = Sheet4.Range("g" & Rows.Count).End(xlUp).Row
    c = 0
    For x = 2 To lastrow
        If Sheet4.Cells(x, 10) = Sheet4.Cells(x, 12) Then
            c = c + 1
        End If
    Next x
End Sub

2 个答案:

答案 0 :(得分:3)

检查Col 10或Col 12中的一个单元格。它们有一个公式错误。 #NA#DIV/0!或其他内容因此可能就是您获得Run Time Error 13 Type Mismatch Error的原因。

检查哪个单元格的最佳方法是在发生错误时找到x的值。

以下是复制问题的示例

=0/0放入单元格A1并运行此代码。

enter image description here

修改要查找问题所在的行,请尝试这一点。

Sub summary()
    Dim lastrow As Long
    Dim c As Long, x As Long

    On Error GoTo Whoa

    With Sheet4
        lastrow = .Range("g" & .Rows.Count).End(xlUp).Row

        c = 0
        For x = 2 To lastrow
            If .Cells(x, 10) = .Cells(x, 12) Then
                c = c + 1
            End If
        Next x
    End With

    Exit Sub
Whoa:
    MsgBox "At the time of error the value of x is " & x
End Sub

答案 1 :(得分:1)

Sub summary()
Dim lastrow As Variant
dim c as integer
 lastrow = sheets("Sheet4").Range("g" & Rows.Count).End(xlUp).Row

c = 0

For x = 2 To lastrow

If sheets("Sheet4").Cells(x, 10) = sheets("Sheet4").Cells(x, 12) Then


c = c + 1

End If
Next x
end sub
相关问题