简体   繁体   中英

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

This is my code that I'm currently the error on.

The error is Excel VBA runtime error "13 type mismatch .

The line the error is on: If ActiveCell.Value - ActiveCell.Offset(-1, 0).Value < 0 Then

This code had worked on previous worksheets, but when I import this macro onto a new worksheet, it doesn't seem to work. All the solution I have found on SO don't seem to apply to my circumstance, so any help on this problem would be greatly appreciated.

A sample of the data I'm using:
在此处输入图片说明

In general, On Error Resume Next is something that you should be extremely careful with.

If you put it in your code, it would start ignoring errors and if someone works with code after you he would not be happy at all (or he would think you are an amateur or job-defender). Having said that, CPearson has a good article about it, that's worthy to read - http://www.cpearson.com/excel/errorhandling.htm

Last but not least, make sure that you change On Error Resume Next to something else, once you realize why the errors are happening.

In your case, its a good idea to use the IsNumeric function, to avoid the TypeMismatch Error. If other errors appear, try to avoid them with a similar matter.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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