Home » excel » excel – Run Time Error: 13 showing while looking through #N/A string

excel – Run Time Error: 13 showing while looking through #N/A string

Posted by: admin May 14, 2020 Leave a comment

Questions:

I’m trying to run the below code to find whether the A column has keyword “SUP ID” or not. Any instance of SUP ID would be updated with number 1 on adjacent column and rest all would go as 0. However while finding the #N/A word, getting error Run-Time Error ’13’: Type Mismatch

Sub m()

For i = 2 To 10
    If Cells(i, 1).Value = "SUP ID" Then
        Cells(i, 2).Value = 1
    Else
        Cells(i, 2).Value = 0
    End If
Next i

End Sub

enter image description here

How to&Answers:

You will need to check for the error before the existing if:

Sub m()    
    With ActiveSheet        'Better to use actual sheet: WorkSheets("Sheet1")
        'load with all `0`
        .range("B2:B10").Value = 0
        For i = 2 To 10
            If Not IsError(.Cells(i, 1)) Then
                If .Cells(i, 1).Value = "SUP ID" Then
                    .Cells(i, 2).Value = 1
                End If
            End If
        Next i
    End with        
End Sub

With only 9 cells to check the above will run quickly, but as the range increases the number of times that vba references the worksheet will slow it down.

You can use Arrays to speed it up.

Sub m()
    With ActiveSheet        'Better to use actual sheet: WorkSheets("Sheet1")
        Dim inputArr() As Variant
        inputArr = .Range("A2:A10").Value

        'Default of Integer is `0`
        Dim outputArr() As Integer
        ReDim outputArr(1 To UBound(inputArr, 1), 1 To 1) As Integer


        For i = LBound(inputArr, 1) To UBound(inputArr, 1)
            If Not IsError(inputArr(i, 1)) Then
                If inputArr(i, 1) = "SUP ID" Then
                    outputArr(i, 1) = 1
                End If
            End If
        Next i

        .Range("B2").Resize(UBound(inputArr, 1)).Value = outputArr
    End With
End Sub