繁体   English   中英

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

[英]Excel VBA runtime error '13' type mismatch

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

这段代码已经在以前的工作表上工作了,但是当我将此宏导入到新的工作表上时,它似乎不起作用。 我在SO上找到的所有解决方案似乎都不适用于我的情况,因此,对此问题的任何帮助将不胜感激。

我正在使用的数据样本:
在此处输入图片说明

通常,您应该非常小心“ 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

暂无
暂无

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

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