Excel VBA运行时错误“13”types不匹配

Sub compareLines() Application.ScreenUpdating = False ActiveSheet.Cells(3, 3).Activate While ActiveCell.Value <> "" If ActiveCell.Value - ActiveCell.Offset(-1, 0).Value < 0 Then ActiveCell.EntireRow.Delete Else ActiveCell.Offset(1, 0).Activate End If Wend Application.ScreenUpdating = True End Sub 

这是我的代码,我目前的错误。

错误是Excel VBA runtime error "13 type mismatch

错误所在的行: If ActiveCell.Value - ActiveCell.Offset(-1, 0).Value < 0 Then

此代码已经在以前的工作表,但是当我把这个macros导入到一个新的工作表,它似乎并没有工作。 所有我find的解决scheme似乎不适用于我的情况,所以任何帮助这个问题将不胜感激。

我正在使用的数据示例:
在这里输入图像说明

一般来说, On Error Resume Next是你应该非常小心的事情。

如果你把它放在你的代码中,它会开始忽略错误,如果有人在你之后使用代码,他根本就不会高兴(或者他会认为你是一个业余或者工作防御者)。 话虽如此,CPearson有一个很好的文章,值得一读 – http://www.cpearson.com/excel/errorhandling.htm

最后但并非最不重要的一点是,一旦你意识到错误发生的原因,确保你改变了On Error Resume Next

在你的情况下,使用IsNumeric函数是一个好主意,以避免TypeMismatch错误。 如果出现其他错误,请尽量避免使用类似的问题。

 Dim v1 as Range, v2 as Range While ActiveCell.Value <> "" Set v1 = ActiveCell.Value Set v2 = ActiveCell.Offset(-1) If IsNumeric(v1) And IsNumeric(v2) Then 'Both are numeric, so it's safe to perform arithmetic against these values If v1 - v2 < 0 Then ActiveCell.EntireRow.Delete Else ActiveCell.Offset(1, 0).Activate End If Else: ActiveCell.Offset(1, 0).Activate End If Wend