2015-05-21 32 views
1

我在尝试找出为什么下面的代码给我一个Error '13'时遇到了很多麻烦。难道我做错了什么?For循环中的If语句中的类型不匹配

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 
+0

我的建议是将'Sheet4'换成'Sheets(“Sheet4”)''。如果你想参考你在工作簿中看到的工作表名称,应该总是使用后一个选项,因为“Sheet4”光秃秃的不一样。 – ZygD

+0

您将变量'last'设置为变体数据类型,但永远不会使用它。如果你打算用它来保存lastrow变量,除了改变变量名称以匹配外,我会使用长数据类型,而不是变化较慢的数据类型,并占用更多的内存。 – DyRuss

+0

@DyRuss - 也许他使用它,因为在原始代码版本中没有'End Sub'。 – ZygD

回答

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 
+1

还有更多'Sheet4'的实例。你应该考虑将所有裸“Sheet4”改为“Sheets(”Sheet4“)”,而不仅仅是第一个。 – ZygD

+0

肯定sry只有很多律所有 – KKowalczyk

+0

完成希望:) – KKowalczyk

3

检查一个你的细胞在10中校或上校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 
+0

更好的解决方案:) – KKowalczyk

+0

要修复它的懒惰的方式,只需添加:'如果.Cells(x,10)= .Cells(x,12)然后'然后添加On在'End If'错误后转到0' – user1274820

+1

这是一个非常错误的建议@ user1274820 :) –